package com.qianmi.hardwarekit.sunmi.dsd;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qianmi.hardwarekit.R;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import sunmi.ds.DSKernel;
import sunmi.ds.FilesManager;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.IReceiveCallback;
import sunmi.ds.data.DSData;
import sunmi.ds.data.DSFile;
import sunmi.ds.data.DSFiles;

/**
 * Created by xiayinglin on 2017/6/23.
 */
public class DsdWebActivity extends Activity {

    private DSKernel mDSKernel;
    private WebView mWebView;
    private Gson gson = new Gson();
    private FilesManager mFilesManager;

    static final int PERMISSION_EXTERNAL_STORAGE = 100;

    private static final String PREFFIX_ASSET = "file:///android_asset/";

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_webview);
        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.getSettings().setJavaScriptEnabled(true);//启用js
        mWebView.getSettings().setBlockNetworkImage(false);//解决图片不显示
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.getSettings().setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            mWebView.addJavascriptInterface(new JavascriptFunction(), "client");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        permission();
//        new HtmlTask().execute(PREFFIX_ASSET + "index.html");
        mDSKernel = DSKernel.newInstance();
        mDSKernel.init(this, mConnCallback);
        mDSKernel.addReceiveCallback(mReceiveCallback);
        mFilesManager = FilesManager.getInstance();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_EXTERNAL_STORAGE: {
                // 如果请求被拒绝，那么通常grantResults数组为空
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //申请成功，进行相应操作
                    new HtmlTask().execute(PREFFIX_ASSET + "index.html");
                } else {
                    //申请失败，可以继续向用户解释。
                    Toast.makeText(this, R.string.permission_sd_msg, Toast.LENGTH_SHORT).show();
                    new HtmlTask().execute(PREFFIX_ASSET + "dsd.permission.html");
                }
            }
        }
    }

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

    /**
     * SDK链接状态回调
     */
    private IConnectionCallback mConnCallback = new IConnectionCallback() {
        @Override
        public void onDisConnect() {
            Toast.makeText(getBaseContext(), "断开连接!", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onConnected(ConnState arg0) {
            switch (arg0) {
                case AIDL_CONN:
                    Log.d(getClass().getSimpleName(), "===== AIDL_CONN =====");
                    // Toast.makeText(getBaseContext(), "与本地service连接正常!", Toast.LENGTH_LONG).show();
                    break;
                case VICE_SERVICE_CONN:
                    Log.d(getClass().getSimpleName(), "===== VICE_SERVICE_CONN =====");
                    // Toast.makeText(getBaseContext(), "与副屏service连接正常!", Toast.LENGTH_LONG).show();
                    break;
                case VICE_APP_CONN:
                    Log.d(getClass().getSimpleName(), "===== VICE_APP_CONN =====");
                    // Toast.makeText(getBaseContext(), "与副屏APP连接正常!", Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 接收数据的回调
     */
    private IReceiveCallback mReceiveCallback = new IReceiveCallback() {

        @Override
        public void onReceiveFile(DSFile file) {
            Log.d(getClass().getSimpleName(), "IReceiveCallback.onReceiveFile:" + file.path);
            mFilesManager.saveFile(file);
        }

        @Override
        public void onReceiveFiles(DSFiles dsFiles) {
            Log.d(getClass().getSimpleName(), "IReceiveCallback.onReceiveFiles:" + dsFiles.files);
            mFilesManager.saveFiles(dsFiles);
        }

        @Override
        public void onReceiveData(final DSData dsData) {
            Data d = gson.fromJson(dsData.data, Data.class);
            Log.d(getClass().getSimpleName(), "onReceiveData:" + dsData.data);
            switch (d.dataModel) {
                case TEXT:
                    try {
                        if (!TextUtils.isEmpty(d.data) && null != mWebView) {
                            Log.d(getClass().getSimpleName(), "TEXT: " + d.data);
                            WebJsonData webJsonData = gson.fromJson(d.data, WebJsonData.class);
                            if (null == webJsonData) return;
                            if (null != webJsonData.getUrl()) {
                                mWebView.loadUrl(webJsonData.getUrl());
                            } else if (-1 != webJsonData.getTaskId()) {
                                Log.d(getClass().getSimpleName(), "getTaskId -> " + webJsonData.getTaskId());
                                DSFile dsf = mFilesManager.getFile(webJsonData.getTaskId());
                                Log.d(getClass().getSimpleName(), "taskId loadFile -> " + dsf.path);
                                Integer way = webJsonData.getWay();
                                Log.d(getClass().getSimpleName(), "getWay -> " + webJsonData.getWay());
                                if (null == way || 0 == way) {
                                    mWebView.loadUrl("file://" + dsf.path);
                                } else {
                                    new HtmlTask().execute(dsf.path);
                                }
                            } else if (!TextUtils.isEmpty(webJsonData.getSource())) {
                                Log.d(getClass().getSimpleName(), "getSource -> " + webJsonData.getSource());
                                mWebView.loadData(webJsonData.getSource(), "text/html", "UTF-8");
                            } else if (!TextUtils.isEmpty(webJsonData.getScript())) {
                                Log.d(getClass().getSimpleName(), "getScript -> " + webJsonData.getScript());
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    Log.d(getClass().getSimpleName(), "evaluateJavascript -> " + webJsonData.getScript());
                                    mWebView.evaluateJavascript(webJsonData.getScript(), new ValueCallback<String>() {
                                        @Override
                                        public void onReceiveValue(String value) {
                                            Log.d(getClass().getSimpleName(), value);
                                        }
                                    });
                                } else {
                                    Log.d(getClass().getSimpleName(), "loadUrl -> " + webJsonData.getScript());
                                    mWebView.loadUrl("javascript:" + webJsonData.getScript());
                                }
                            }
                        }
                    } catch (Exception e) {
                        Log.e(getClass().getSimpleName(), e.getLocalizedMessage());
                        Toast.makeText(DsdWebActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onReceiveCMD(DSData cmd) {

        }
    };


    /**
     * 追加相关副屏幕h5到webview中
     */
    private class HtmlTask extends AsyncTask<String, Integer, String> {


        @Override
        protected String doInBackground(String... params) {
            String path = params[0];
            try {
                Document doc = document(path);
                if (!path.endsWith("dsd.permission.html")) {
                    doc.head().append("<link rel=\"stylesheet\" type=\"text/css\" href=\"index_dsd.css\" />");
                    doc.head().append("<script type=\"text/javascript\" src=\"index_dsd.js\" /></script>");
                    doc.body().append(getAssets("index_dsd.html"));
                }
                return doc.html();
            } catch (IOException e) {
//                Log.e(getClass().getSimpleName(), e.getLocalizedMessage());
//                return "<html><body>FileNotFoundException<br> " + e.getLocalizedMessage() + "</body></html>";
                try {
                    Document doc = document("file:///android_asset/dsd.permission.html");
                    return doc.html();
                } catch (IOException e1) {
                    Log.e(getClass().getSimpleName(), e1.getLocalizedMessage());
                }
                return null;
            }
        }


        @Override
        protected void onPostExecute(String source) {
            super.onPostExecute(source);
            if (null != source) {
                mWebView.loadDataWithBaseURL("file:///android_asset/", source, "text/html", "UTF-8", null);
            }
        }

        private Document document(String path) throws IOException {
            byte[] buffer;
            if (path.startsWith(PREFFIX_ASSET)) {
                buffer = getAssets(path.substring(PREFFIX_ASSET.length(), path.length())).getBytes();
            } else {
                FileInputStream fin = new FileInputStream(path);
                int length = fin.available();
                buffer = new byte[length];
                int count = fin.read(buffer);
                Log.d(getClass().getSimpleName(), "read file length ====>" + count);
            }

            return Jsoup.parse(new String(buffer, "UTF-8"));
        }
    }


    public String getAssets(String name) throws IOException {
        InputStream ins = getAssets().open(name);
        byte[] as = new byte[ins.available()];
        int count = ins.read(as);
        if (0 < count) {
            return new String(as);
        }
        return "";
    }


    class JavascriptFunction {

        @JavascriptInterface
        public void permission() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(DsdWebActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(DsdWebActivity.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//
//                //进行权限请求
                    ActivityCompat.requestPermissions(DsdWebActivity.this, new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                    }, PERMISSION_EXTERNAL_STORAGE);
                } else {
                    new HtmlTask().execute(PREFFIX_ASSET + "index.html");
                }
            }
        }
    }

    private void permission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    Toast.makeText(this, R.string.permission_sd_msg, Toast.LENGTH_SHORT).show();
                }
//
//                //进行权限请求
//                ActivityCompat.requestPermissions(this, new String[]{
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_EXTERNAL_STORAGE
//                }, PERMISSION_EXTERNAL_STORAGE);
                new HtmlTask().execute(PREFFIX_ASSET + "dsd.permission.html");
            } else {
                new HtmlTask().execute(PREFFIX_ASSET + "index.html");
            }
        }
    }

}
