package com.gem.media;

import static com.gem.media.util.UACreator.createUA;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.ads.cal.picturetranslate.R;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.util.BarUtils;
import com.gem.media.util.KeyboardUtils;
import com.gem.media.util.ScreenUtils;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class HActivity extends Activity {


    /**
     * URI scheme for telephone number.
     */
    private static final String SCHEME_TEL = "tel:";
    private static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
            "(?i)" + // switch on case insensitive matching
                    "(" +    // begin group for schema
                    "(?:http|https|file):\\/\\/" +
                    "|(?:inline|data|about|javascript):" +
                    ")" +
                    "(.*)");

    private static final Pattern QUERY_URL = Pattern.compile("\\{[^}]*\\}");

    private boolean isGooglePlay(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        return url.startsWith("https://play.google.com/store/apps/details");
    }

    private final static String URL_1 = "https://seekspotter.com";
    private final static String URL_2 = "https://animalslove-info.s1search.co";


    private WebView webView;
    private ProgressBar mProgressBar;
    private LinearLayout layout;
    private String url;
    private final static String REPLACE_URL = "{query}";
    private LinearLayout topContent;
    private LinearLayout topSearch;
    private ImageView iconSearch;
    private TextView textSearch;
    private ImageView line;


    private void onCreateReport() {
        Map<String, String> map = new HashMap<>();
        if (url == null) {
            map.put("url", "url is null");
        } else {
            map.put("url", url);
        }
        map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
        StatsStaticHelper.onEvent(Constants.H_CREATE, map);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        // 设置导航栏图标颜色（API 26+）
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                View decorView = window.getDecorView();
                int flags = decorView.getSystemUiVisibility();
                flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
                decorView.setSystemUiVisibility(flags);
            }
        } catch (Exception e) {
            ALog.d("HActivity", "e -- "+e.getMessage());
        }
        ALog.d("HActivity", "onCreate");
        setContentView(R.layout.h_layout);
        getData();
        onCreateReport();
        if (TextUtils.isEmpty(url)) {
            ALog.d("HActivity", "url = null");
            finish();
            return;
        }
        ALog.d("HActivity", "url " + url);
        BarUtils.setStatusBarColor(this, Color.WHITE);
        BarUtils.setStatusBarLightMode(this, true);
        EditText editText = findViewById(R.id.edtext);
        line = findViewById(R.id.line);
        topSearch = findViewById(R.id.topsearch);
        iconSearch = findViewById(R.id.search_icon);
        textSearch = findViewById(R.id.search_text);
        mProgressBar = findViewById(R.id.launch_progress);
        layout = findViewById(R.id.layout);
        topContent = findViewById(R.id.top_content);
        int h = ScreenUtils.getScreenHeight();
        int w = ScreenUtils.getScreenWidth();
        if (h < w) {
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(h, FrameLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
            topContent.setLayoutParams(layoutParams);
        }
        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    if (webView != null) {
                        webView.onPause();
                    }
                    finish();
                }
            }
        });
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 在这里执行回车按钮按下时的操作
                    if (null != webView && !isFinished) {
                        try {
                            String text = editText.getText().toString();
                            if (TextUtils.isEmpty(text) || text.equals("null") || text.equals(REPLACE_URL)) {
                                text = "gmail";
                            }
                            String endUrl = url.replace(REPLACE_URL, text);
                            ALog.d("HActivity", "endUrl --->  " + endUrl);
                            webView.loadUrl(endUrl);
                            KeyboardUtils.hideSoftInput(editText);
                            Map<String, String> map = new HashMap<>();
                            map.put("url", endUrl);
                            map.put("text", text);
                            map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
                            StatsStaticHelper.onEvent(Constants.H_PAGE_SEARCH_TEXT, map);
                        } catch (Exception e) {

                        }

                    }
                    return true; // 返回true表示已处理该事件
                }
                return false;
            }
        });
        editText.requestFocus();
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
            }
        }, 200);
        webView = new WebView(this);
        webView.setBackgroundColor(Color.WHITE);
        ALog.d("HActivity", "setWebChromeClient");
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                ALog.d("HActivity", "onProgressChanged  " + newProgress);
                if (newProgress >= 100) {
//                    mProgressBar.setVisibility(View.GONE);
                } else {
                    if (isFinished) {
                        return;
                    }
                    if (mProgressBar.getVisibility() != View.VISIBLE) {
                        mProgressBar.setVisibility(View.VISIBLE);
                    }
                    mProgressBar.setProgress(newProgress);
                }
            }
        });
        ALog.d("HActivity", "WebViewClient");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                // 获取要跳转的URL
                String url = request.getUrl().toString();
                ALog.d("HActivity", url);
                Matcher m = ACCEPTED_URI_SCHEMA.matcher(url);
                if (isGooglePlay(url) || !m.matches()) {
                    try {
                        // 解析Intent并启动相应的第三方APP
                        Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        if (intent != null) {
                            view.getContext().startActivity(intent);
                            return true;
                        }
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                        ALog.d("HActivity", e.getMessage());

                    }
                } else if (url.startsWith("https://download")) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                        return true;
                    } catch (Exception e) {
                        e.printStackTrace();
                        ALog.d("HActivity", e.getMessage());
                    }
                } else if (url.startsWith(SCHEME_TEL)) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW,
                                Uri.parse(SCHEME_TEL
                                        + url.substring(SCHEME_TEL.length())));
                        startActivity(intent);
                        return true;
                    } catch (Exception e) {
                        e.printStackTrace();
                        ALog.d("HActivity", e.getMessage());
                    }
                }

                boolean isReturn = true;
                Intent intent = null;
                // perform generic parsing of the URI to turn it into an Intent.
                try {
                    intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                } catch (URISyntaxException ex) {
                    isReturn = false;
                    ALog.e("HActivity", "Bad URI " + url + ": " + ex.getMessage());
                }
                if (null != intent) {
                    if (getPackageManager() != null
                            && getPackageManager().resolveActivity(intent, 0) == null) {
                        String packagename = intent.getPackage();
                        if (packagename != null) {
                            intent = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("market://search?q=pname:" + packagename));
                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                        } else if (intent.getData() != null) {
                            intent = new Intent(Intent.ACTION_VIEW, intent.getData());
                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                            isReturn = false;
                        }
                    } else {
                        isReturn = false;
                    }
                } else {
                    isReturn = false;
                }
                if (isReturn) {
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, request);
                }

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                ALog.d("HActivity", "onPageStarted " + url);
                if (!url.startsWith(URL_1) && !url.startsWith(URL_2)) {
                    if (topSearch.getVisibility() != View.GONE) {
                        topSearch.setVisibility(View.GONE);
                    }
                    if (iconSearch.getVisibility() != View.GONE) {
                        iconSearch.setVisibility(View.GONE);
                    }
                    if (textSearch.getVisibility() != View.GONE) {
                        textSearch.setVisibility(View.GONE);
                    }
                }

                try {
                    Map<String, String> map = new HashMap<>();
                    map.put("url", url);
                    map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
                    StatsStaticHelper.onEvent(Constants.H_PAGE_START, map);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!url.startsWith(URL_1) && !url.startsWith(URL_2)) {
                    if (mProgressBar.getVisibility() != View.GONE) {
                        mProgressBar.setVisibility(View.GONE);
                    }
//                    if (topContent.getVisibility() != View.GONE) {
//                        topContent.setVisibility(View.GONE);
//                    }
                    if (line.getVisibility() != View.GONE) {
                        line.setVisibility(View.GONE);
                    }
                }
                ALog.d("HActivity", "onPageFinished");
                try {
                    Map<String, String> map = new HashMap<>();
                    map.put("url", url);
                    map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
                    StatsStaticHelper.onEvent(Constants.H_PAGE_FINISH, map);
                } catch (Exception e) {

                }
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                try {
                    Map<String, String> map = new HashMap<>();
                    map.put("url", view.getUrl());
                    map.put("r", errorResponse.getReasonPhrase());
                    map.put("code", String.valueOf(errorResponse.getStatusCode()));
                    map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
                    StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
                } catch (Exception e) {

                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                try {
                    Map<String, String> map = new HashMap<>();
                    map.put("url", error.getUrl());
                    map.put("r", "onReceivedSslError");
                    map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
                    StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
                } catch (Exception e) {

                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                try {
                    Map<String, String> map = new HashMap<>();
                    map.put("url", failingUrl);
                    map.put("r", description);
                    map.put("code", String.valueOf(errorCode));
                    map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
                    StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
                } catch (Exception e) {

                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                try {
                    Map<String, String> map = new HashMap<>();
                    map.put("url", view.getUrl());
                    map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        map.put("r", error.getDescription().toString());
                    }
                    StatsStaticHelper.onEvent(Constants.H_PAGE_ERROR, map);
                } catch (Exception e) {

                }
            }
        });
        WebSettings settings = webView.getSettings();
        settings.setGeolocationEnabled(true);
        settings.setJavaScriptEnabled(true);

        settings.setDefaultFontSize(16);
        settings.setDefaultFixedFontSize(13);
        settings.setTextZoom(100);

        settings.setLoadWithOverviewMode(true);// CR01455967

        // WebView inside Browser doesn't want initial focus to be set.
        settings.setNeedInitialFocus(false);
        // Browser supports multiple windows
        // settings.setSupportMultipleWindows(true);
        // enable smooth transition for better performance during panning or
        // zooming
        settings.setEnableSmoothTransition(true);
        // disable content url access
        settings.setAllowContentAccess(true);

        // display
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        settings.setSavePassword(true);
        settings.setSaveFormData(true);

        ALog.d("HActivity", "createUA() = " + createUA());
        ALog.d("HActivity", "getUserAgentString() = " + settings.getUserAgentString());

        if (TextUtils.isEmpty(settings.getUserAgentString())) {
            settings.setUserAgentString(createUA());
        }


        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        layout.removeAllViews();
        layout.addView(webView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        ALog.d("HActivity", "add webView");
        Matcher m = QUERY_URL.matcher(url);
        if (!m.find()) {
            if (topSearch.getVisibility() != View.GONE) {
                topSearch.setVisibility(View.GONE);
            }
            if (iconSearch.getVisibility() != View.GONE) {
                iconSearch.setVisibility(View.GONE);
            }
            if (textSearch.getVisibility() != View.GONE) {
                textSearch.setVisibility(View.GONE);
            }

            webView.loadUrl(url);
        }
    }

    private long currentTime;

    @Override
    protected void onResume() {
        super.onResume();
        currentTime = System.currentTimeMillis();
    }


    @Override
    protected void onPause() {
        ALog.d("HActivity", "onPause");
        if (webView != null) {
            webView.onPause();
        }
        super.onPause();
    }

    private boolean isFinished = false;

    @Override
    protected void onStop() {
        if (!isFinished) {
            finish();
        }
        super.onStop();
        Map<String, String> map = new HashMap<>();
        long t = (System.currentTimeMillis() - currentTime) / 1000;
        map.put("t", String.valueOf(t));
        map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
        StatsStaticHelper.onEvent(Constants.H_SHOW_TIME, map);
        ALog.d("HActivity", "onStop");
    }

    @Override
    public void finish() {
        if (isFinished) {
            super.finish();
            return;
        }
        isFinished = true;
        super.finish();
    }

    private String from;

    private void getData() {
        Intent intent = getIntent();
        if (null != intent) {
            url = intent.getStringExtra("url");
            from = intent.getStringExtra("from");
            if (TextUtils.isEmpty(from)) {
                from = "old";
            }
            ALog.d("HActivity", "url = " + url + "  from  " + from);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ALog.d("HActivity", "onDestroy");
        clearData();
    }

    private void clearData() {
        if (null != webView) {
            if (null != layout) {
                webView.stopLoading();
                webView.loadUrl("about:blank");
                layout.removeView(webView);
            }
            webView.destroy();
            webView = null;
        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}
