package com.bokecc.dwlivedemo.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


import com.bokecc.dwlivedemo.R;
import com.bokecc.livemodule.utils.NetworkUtils;
import com.bokecc.sdk.mobile.live.DWLiveEngine;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class NetworkCheckActivity extends Activity {


    private static final String TAG = "NetworkCheckActivity";
    private WebView webView;

    private Handler handler = new Handler(Looper.myLooper());

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network_check);
        webView = findViewById(R.id.webView);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        // 优先渲染界面
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 自动播放
        settings.setMediaPlaybackRequiresUserGesture(false);
        // 不支持缩放
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        // 设置WebView字体按照Normal形式展示
        settings.setTextZoom(100);
        // 只使用网络的数据，不使用缓存
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // WebView 默认都是支持cookies
        CookieManager.getInstance().setAcceptCookie(true);
        /*
         * 支持HTTPS、HTTP混合模式
         * http://blog.csdn.net/qq_16472137/article/details/54346078
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        /* 支持cookies 5.0以上的手机不支持自动同步第三方cookies
         *（一般都是iframe里面的页面要存储cookies操作的设置）
         * http://blog.sina.com.cn/s/blog_6e73239a0102viku.html
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        }
        // 设置和js交互接口
        webView.addJavascriptInterface(new MyJavaScriptInterface(this,handler), "android");

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.i(TAG,"onPageStarted:"+url);

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG,"onPageFinished:"+url);

                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.i(TAG,"shouldOverrideUrlLoading");

                return super.shouldOverrideUrlLoading(view, request);
            }
        });


        webView.loadUrl("https://doctor.bokecc.com/#/webview?terminal=android");

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

    public class MyJavaScriptInterface {

        private Context context;
        private Handler handler;

        public MyJavaScriptInterface(Context context,Handler handler) {
            this.context = context;
            this.handler = handler;
        }

        @JavascriptInterface
        public void getBaseInfo(String data){
            Log.i(TAG,"getBaseInfo");
            handler.post(new Runnable() {
                @Override
                public void run() {
                    HashMap<String,String> map = new HashMap<>();
                    map.put("sdkVersion", DWLiveEngine.VERSION);
                    map.put("model", Build.MODEL);
                    map.put("system", Build.VERSION.RELEASE);
                    map.put("networkType", NetworkUtils.getNetworkType(context));
                    JSONObject jsonObject = new JSONObject(map);
                    String s = "javascript:window.recieveBaseInfo("+jsonObject.toString()+")";
                    Log.i(TAG,s);
                    evaluateJs(s);
                }
            });


        }
    }



    private void evaluateJs(String instruct) {
        if (TextUtils.isEmpty(instruct)) {return;}
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.evaluateJavascript(instruct, null);
        } else {
            webView.loadUrl(instruct);
        }
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
