package com.ym.unityandroid.webview;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.unity3d.player.R;

public class UnityWebActivity extends Activity {
    private String url;
    private UnityCustomWebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.unity_activity_web);
        url = getIntent().getStringExtra("url");
        //title =  getIntent().getStringExtra("title");
        webView = findViewById(R.id.activity_webview);
        initTitle();
        initWebView();
        webView.loadUrl(url);
    }
    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
//        webView.getSettings().setDefaultFontSize(56);
        // webView.getSettings().setMinimumFontSize(40);//设置最小字体
        // 建议禁止缓存加载，以确保在攻击发生时可快速获取最新的滑动验证组件进行对抗。
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置不使用默认浏览器，而直接使用WebView组件加载页面。
        // 设置WebView组件支持加载JavaScript。
        webView.getSettings().setJavaScriptEnabled(true);
        // 建立JavaScript调用Java接口的桥梁。
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        try {
            // API 7, LocalStorage/SessionStorage
            webSettings.setDomStorageEnabled(true);
            webSettings.setDatabaseEnabled(true);
//            webSettings.setDatabasePath(HcAppliContext.get().filesDir.absolutePath + "/webcache");
            // API 7， Web SQL Database, 需要重载方法（WebChromeClient）才能生效，无法只通过反射实现
        } catch (Exception e) {
        }
        webView.setWebChromeClient(new WebChromeClient(){

            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                WebView.WebViewTransport transport = (WebView.WebViewTransport)resultMsg.obj;
                transport.setWebView(webView);
                resultMsg.sendToTarget();
                return true;
            }
        });
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url!=null){
                    if (shouldOverrideUrlLoadingByApp(url)) {
                        return true;
                    }
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

    }

    private void initTitle() {

        findViewById(R.id.iv_user_toolbar_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            webView.loadUrl("javascript:onResume()");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.loadUrl("javascript:onPause()");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.destroy();
        }
    }


    private boolean shouldOverrideUrlLoadingByApp(String url){
        try {
            if (!url.startsWith("http") && !url.startsWith("https") && !url.startsWith("ftp")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                if (isInstall(intent)) {
                    this.startActivity(intent);
                    return true;
                }
            } else {
                return false;
            }
        } catch (Exception e ) {
            return false;
        }

        return false;
    }
    //判断app是否安装
    public static Boolean isInstall(Intent intent) {
        return false;
    }

}