package com.meeting.demo.view.webview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.meeting.demo.R;
import com.huawei.hwmfoundation.Foundation;
import com.huawei.hwmlogger.HCLog;

public class WebViewActivity extends Activity {
    private static final String TAG = WebViewActivity.class.getSimpleName();

    public static final int ACTION_GET_CODE = 100001;

    private WebView mWebview;

    private String requestUrl;

    private int action;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        Intent intent = getIntent();
        if (intent != null) {
            requestUrl = Uri.decode(intent.getStringExtra("requestUrl"));
            action = intent.getIntExtra("action", 0);
        }
        initView();
    }

    @Override
    public void onBackPressed() {
        onBack();
    }

    private void onBack() {
        if (mWebview.canGoBack()) {
            mWebview.goBack();
        } else {
            finish();
        }
    }

    public void initView() {
        mWebview = findViewById(R.id.webview);
        mWebview.setWebViewClient(new WebViewClient() {

            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedHttpError(WebView webView, WebResourceRequest request,
                WebResourceResponse errorResponse) {
                super.onReceivedHttpError(webView, request, errorResponse);
            }

            @Override
            public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
                super.onReceivedError(webView, errorCode, description, failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler handler, SslError error) {
                if (handler == null) {
                    HCLog.i(TAG, "SslErrorHandler is null");
                    return;
                }
                handler.proceed();

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                HCLog.i(TAG, url);
                if (url.contains("inappbrowserref_close_url")) {
                    finish();
                }
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    if (action == ACTION_GET_CODE) {
                        String code = getCode(url);
                        if (code != null) {
                            setCodeResult(code);
                            finish();
                            return true;
                        }
                    }
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    String url = request.getUrl().toString();
                    HCLog.i(TAG, url);
                    if (action == ACTION_GET_CODE) {
                        String code = getCode(url);
                        if (code != null) {
                            setCodeResult(code);
                            finish();
                            return true;
                        }
                    }

                    try {
                        if (!url.startsWith("http://") && !url.startsWith("https://")) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                            startActivity(intent);
                            return true;
                        }
                    } catch (Exception e) {
                        return true;
                    }
                }

                return super.shouldOverrideUrlLoading(view, request);
            }
        });
        WebSettings webSettings = mWebview.getSettings();
        if (!requestUrl.startsWith("https://")) {
            mWebview.getSettings().setJavaScriptEnabled(false);
            Foundation.getUTHandle().addUTInvalidUrl(requestUrl);
        } else {
            mWebview.getSettings().setJavaScriptEnabled(true);
        }
        webSettings.setDomStorageEnabled(true);
        mWebview.loadUrl(requestUrl);
    }

    private void setCodeResult(String code) {
        Intent data = new Intent();
        data.putExtra("result", code);
        setResult(Activity.RESULT_OK, data);
    }

    private String getCode(String url) {
        if (url != null && url.startsWith("hwmuisdk://demosoftclient/h5page")) {
            String[] arr = url.split("&");
            for (String param : arr) {
                if (param.startsWith("code=")) {
                    return param.substring(5);
                }
            }
        }
        return null;
    }
}

