package com.gem.media;

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

import android.app.Activity;
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.View;
import android.view.Window;
import android.view.WindowManager;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

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 java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NewHActivity 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 boolean isGooglePlay(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        return url.startsWith("https://play.google.com/store/apps/details");
    }

    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);
    }

    private WebView webView;
    private ProgressBar mProgressBar;
    private LinearLayout layout;
    private int i = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (i == 0) {
            finish();
            return;
        }
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        ALog.d("NewHActivity", "onCreate");
        setContentView(R.layout.n_h_layout);
        getData();
        onCreateReport();
        if (TextUtils.isEmpty(url)) {
            ALog.d("NewHActivity","url = null");
            finish();
            return;
        }
        ALog.d("NewHActivity","url = " + url);
        BarUtils.setStatusBarColor(this, Color.BLACK);
        BarUtils.setStatusBarLightMode(this,false);
        mProgressBar = findViewById(R.id.launch_progress);
        layout = findViewById(R.id.layout);
        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();
                }
            }
        });

        webView = new WebView(this);
        webView.setBackgroundColor(Color.WHITE);
        ALog.d("NewHActivity", "setWebChromeClient");
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                ALog.d("NewHActivity", "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("NewHActivity", "WebViewClient");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                // 获取要跳转的URL
                String url = request.getUrl().toString();
                ALog.d("NewHActivity", 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("NewHActivity", 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("NewHActivity", 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("NewHActivity", 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("NewHActivity", "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("NewHActivity", "onPageStarted "+url);
                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);
                ALog.d("NewHActivity", "onPageFinished");
                if (mProgressBar.getVisibility() != View.GONE) {
                    mProgressBar.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_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("NewHActivity","createUA() = "+createUA());
        ALog.d("NewHActivity","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));

        if (null != webView) {
            webView.loadUrl(url);
            Map<String, String> map = new HashMap<>();
            map.put("url", TextUtils.isEmpty(url) ? "url is null" : url);
            map.put("pt", TextUtils.isEmpty(from) ? "old" : from);
            StatsStaticHelper.onEvent(Constants.H_PAGE_SEARCH_TEXT, map);
            ALog.d("NewHActivity", "loadUrl url " + url +"  from  "+from);
        } else {
            ALog.d("NewHActivity","webView = null");
            finish();
        }
        ALog.d("NewHActivity", "add webView");
    }

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


    @Override
    protected void onPause() {
        ALog.d("NewHActivity","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("NewHActivity","onStop");
    }

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

    private String from;
    private String url;

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ALog.d("NewHActivity","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();
        }
    }
}
