package com.unit.websdk;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;

import com.unit.util.GlobalUtil;

public class AdWebView extends WebView {
    private static final String TAG = "AdWebView";
    private String jsBridgeName;
    private boolean isPreload;

    public AdWebView(@NonNull Context context, WebJsBridge webJsBridge, boolean isPreload) {
        super(context);
        this.isPreload = isPreload;
        initView(webJsBridge);
    }

    @Override
    public void destroy() {
        if (!TextUtils.isEmpty(jsBridgeName)) {
            removeJavascriptInterface(jsBridgeName);
        }
        //移除所有附加到webview的视图
        removeAllViews();
        //清除缓存和历史记录
        clearCache(true);
        clearHistory();
        //加载空页
        loadUrl("about:blank");
        //停止加载
        stopLoading();
        super.destroy();
    }

    public boolean isPreload() {
        return isPreload;
    }

    private void initView(WebJsBridge jsBridge) {
        WebSettings webSettings = getSettings();
        webSettings.setAllowFileAccess(true);
        webSettings.setBlockNetworkImage(false);
        webSettings.setBlockNetworkLoads(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);
        webSettings.setDatabaseEnabled(false);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setTextZoom(100);
        webSettings.setGeolocationEnabled(false);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setNeedInitialFocus(true);
        webSettings.setSaveFormData(false);
        webSettings.setSupportMultipleWindows(false);
        webSettings.setSupportZoom(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setCacheMode(android.webkit.WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setLoadWithOverviewMode(true);
        setHorizontalScrollBarEnabled(false);
        setVerticalScrollBarEnabled(false);
        setInitialScale(0);
        setOverScrollMode(OVER_SCROLL_NEVER);
        if (Build.VERSION.SDK_INT >= 16) {
            webSettings.setAllowFileAccessFromFileURLs(true);
            webSettings.setAllowUniversalAccessFromFileURLs(true);
        }
        if (Build.VERSION.SDK_INT >= 17) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            webSettings.setMixedContentMode(1);
        }
        initWebClient();
        initJsBridge(jsBridge);
    }

    private void initJsBridge(WebJsBridge jsBridge) {
        if (jsBridge == null) return;
        jsBridgeName = jsBridge.getJsBridgeName();
        addJavascriptInterface(jsBridge, jsBridge.getJsBridgeName());
    }

    private void initWebClient() {
        // WebView对Url协议头的支持
        setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(@NonNull WebView view, @NonNull WebResourceRequest request) {
                Log.d(TAG, "shouldOverrideUrlLoading, " + request.getUrl());
                if (request.getUrl() != null) {
                    try {
                        if(WebViewUtil.openIntent(GlobalUtil.getMainActivity(), request.getUrl().toString())){
                            return true;
                        }
                    } catch (Throwable e) {
                        return true;
                    }
                }
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
        // apk下载处理
        setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            GlobalUtil.getMainActivity().startActivity(intent);
        });
    }
}
