package chaoran.business.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.View;
import android.webkit.*;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.Map;

import chaoran.business.BrandEnum;
import chaoran.business.R;
import chaoran.business.adapter.*;
import chaoran.business.engine.impl.NetworkSettingEngine;
import chaoran.business.engine.SettingEngine;
import chaoran.business.engine.impl.TekVoiceEngine;
import chaoran.business.engine.VoiceEngine;
import chaoran.business.service.ScanServiceEDA50P;
import chaoran.business.service.ScanServiceZEBRA;
import chaoran.business.utils.LocalAddressUtil;
import chaoran.business.utils.StatusBarUtil;

/**
 * 流程：联网认证设备型号，验证通过，查找设备品牌进行调用驱动操作
 */

/**
 * 提供文字转语音功能，实时播报PDA状态
 */
public class MainActivity extends AppCompatActivity implements ResultListener{

    private WebView webView;
    private Adapter adapter;
    private VoiceEngine voiceEngine;
    private SettingEngine settingEngine;
    private ProgressBar progressBar;
    private ActionBar actionBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        //SCREEN_ORIENTATION_USER，不能旋转180，0、90、270都可以旋转
        //SCREEN_ORIENTATION_FULL_SENSOR 都可以旋转，但是在不打开旋转的情况下，一样可以旋转
        //SCREEN_ORIENTATION_FULL_USER 关闭旋转则不会旋转了
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);

    }

    private void initData() {
        BrandEnum brand = BrandEnum.code(Build.MANUFACTURER);
        Toast.makeText(this, Build.MANUFACTURER, Toast.LENGTH_LONG).show();
        Log.i("brand===",brand.toString());
        switch (brand) {
            case UROBO:
                adapter = new UroBoAdapter(this, this);
                break;
            case ROCKCHIP:
                adapter = new RockChipAdapter(this, this);
                break;
            case IDATA:
                adapter = new IDataAdapter(this, this);
                break;
            case ALPS:
                adapter = new AlpsAdapter(this, this);
                break;
            case SEUIC:
                adapter = new SeuicAdapter(this, this);
                break;
            case HONEY_WELL_EDA50P:
                // 51、56都是同一个code
            case HONEY_WELL_EDA51:
                if ("eda56".equals(Build.MODEL.toLowerCase())) {
                    adapter = new HoneywellEda56Adapter(this, this);
                }else {
                    adapter = new HoneywellAdapter(this, this);
                }
                break;
            case ZEBRA_TECHNOLOGIES:
                adapter = new ZebraAdapter(this, this);
            case HISENSE:
                adapter = new HisenseAdapter(this, this);
            case LACHESIS:
                adapter = new LachesisAdapter(this, this);
            case UROVO:
                adapter = new UrovoAdapter(this, this);
        }
        if (null != adapter) {
            adapter.start();
        }
    }
    @SuppressLint("JavascriptInterface")
    private void initView() {
        actionBar = getSupportActionBar();
        voiceEngine = new TekVoiceEngine(this);
        settingEngine = new NetworkSettingEngine(this);
        webView = findViewById(R.id.webView);
        progressBar = findViewById(R.id.loading);
        webView.setWebViewClient(disposeView());
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);

//        StatusBarUtil.transparencyBar( this); // 设置全部透明，需要在页面设置一个参数进行布局的样式跳转，不同的手机端，状态栏高度不一样（apk设置状态栏高度无效，这个是安卓9的一个bug），所以在此采取隐藏状态栏
        StatusBarUtil.hideStatusBar( this); // 设置全部透明

        //设置接口进行windows暴露
        settings.setDomStorageEnabled(true);
        //语音引擎
        webView.addJavascriptInterface(voiceEngine, "TekVoiceEngine");
        //网络设置展示
        webView.addJavascriptInterface(settingEngine, "NetworkSettingEngine");
        //重新加载页面
        webView.addJavascriptInterface(this, "View");
        webView.addJavascriptInterface(new LocalAddressUtil(this, this, webView), "Localpda");
        webView.loadUrl(url());
    }

    //配置客户端
    private WebViewClient disposeView() {
        return new WebViewClient() {
            //页面开始加载时
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
            }

            //页面加载完成时
            @Override
            public void onPageFinished(WebView view, String url) {
                if (!url.startsWith("file"))
                    actionBar.hide();
                else
                    actionBar.show();
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.INVISIBLE);
            }

            //网络发生错误时,先展示错误界面，然后关闭加载条
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                switch (errorCode) {
                    case 404:
                        webView.loadUrl("file:///android_asset/error/404.html");
                        break;
                    case 500:
                        webView.loadUrl("file:///android_asset/error/500.html");
                        break;
                    default:
                        webView.loadUrl("file:///android_asset/error/index.html");
                }
                actionBar.show();
                actionBar.setTitle(R.string.title_activity_main);
                super.onReceivedError(view, errorCode, description, failingUrl);
                progressBar.setVisibility(View.INVISIBLE);
            }

            //安卓6.0以上发生错误时回调
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    switch (error.getErrorCode()) {
                        case 404:
                            webView.loadUrl("file:///android_asset/error/404.html");
                            break;
                        case 500:
                            webView.loadUrl("file:///android_asset/error/500.html");
                            break;
                        default:
                            webView.loadUrl("file:///android_asset/error/index.html");
                    }
                }
                actionBar.show();
                actionBar.setTitle(R.string.title_activity_main);
                super.onReceivedError(view, request, error);
                progressBar.setVisibility(View.INVISIBLE);
            }
        };
    }


    @Override
    protected void onResume() {
        //再次唤醒该页面时，重新加载页面和语音配置
        //webView.loadUrl(url());
     //   voiceEngine.reload();
        super.onResume();
        if (adapter != null) {
            adapter.stop2();
            adapter.start();
        }
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    public void result(String result) {
        runOnUiThread(() -> webView.loadUrl("javascript:render(\'" + result + "\')"));
    }
    @Override
    protected void onDestroy() {
        if (adapter != null) {
            adapter.stop();
        }
        super.onDestroy();
        if (diPlayer != null) {
            diPlayer.stop();
            diPlayer.release();
            diPlayer = null;
        }
        if (duPlayer != null) {
            duPlayer.stop();
            duPlayer.release();
            duPlayer = null;
        }
        if (dingPlayer != null) {
            dingPlayer.stop();
            dingPlayer.release();
            dingPlayer = null;
        }
        if (vibrator != null) {
            vibrator.cancel();
        }
        completionListener = null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_setting_network:
                startActivity(new Intent(this, NetworkSettingActivity.class));
                break;
            case R.id.action_setting_voice:
                startActivity(new Intent(this, VoiceSettingActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //拼接url
    private String url() {
        SharedPreferences spf = this.getSharedPreferences("crtech", Context.MODE_PRIVATE);
        Integer port = spf.getInt("port", -1);
        if (port == -1) {
            return "file:///android_asset/demo/index.html";
        }
        String address = spf.getString("address", "").replaceAll(" ", "");
        String path = spf.getString("path", "").replaceAll(" ", "");
        String link = address.concat(":").concat(String.valueOf(port)).concat(path);
        return link.startsWith("http://") ? link : "http://".concat(link);
    }

    @JavascriptInterface
    public void reload() {
        runOnUiThread(() -> {
            webView.loadUrl(url());
        });
    }
    private MediaPlayer diPlayer = null;
    private MediaPlayer duPlayer = null;
    private MediaPlayer dingPlayer = null;
    private String ttsNr;
    public Vibrator vibrator;

    @JavascriptInterface
    public void play(String msg, String type, int isZd) throws IOException {
        ttsNr = msg;
        if ("1".equals(type)) {
            if (diPlayer == null) {
                diPlayer = MediaPlayer.create(this, R.raw.didi);
                diPlayer.setOnCompletionListener(completionListener);
            }
            diPlayer.start();
        } else if ("2".equals(type)) {
            if (duPlayer == null) {
                duPlayer = MediaPlayer.create(this, R.raw.dudu);
                duPlayer.setOnCompletionListener(completionListener);
            }
            duPlayer.start();
        } else if ("10".equals(type)) {
            if (dingPlayer == null) {
                dingPlayer = MediaPlayer.create(this, R.raw.ding);
                dingPlayer.setOnCompletionListener(completionListener);
            }
            dingPlayer.start();
        } else {
            //isZd = 1;
            if (voiceEngine != null) {
                voiceEngine.startSpeaking(msg);
            }
        }
        if (isZd == 1) {
            if (vibrator == null) {
                vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            }
            vibrator.vibrate(2000);
        }
    }

    private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        // @Override
        public void onCompletion(MediaPlayer mp) {
            if (ttsNr != null) {
                if (voiceEngine != null) {
                    voiceEngine.startSpeaking(ttsNr);
                }
                ttsNr = null;
            }
        }
    };

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void openIndex() throws IOException {
        runOnUiThread(() -> {
            webView.loadUrl("file:///android_asset/demo/index.html");
        });
    }

    /* 监听角度的变化
    class MyOrientationDetector extends OrientationEventListener {

        private int rotate;

        public MyOrientationDetector(Context context) {
            super(context);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            //假设屏幕旋转被打开。则设置屏幕可旋转
            //0-57度 125-236度 306-360度  这些区间范围内为竖屏
            //58-124度 237-305度  这些区间范围内为横屏
            if (orientation >=0 && orientation <= 57 ) {
                rotate = 1; // 正竖屏
            }else if (orientation >=125 && orientation <= 236 ) {
                rotate = 2; // 倒竖屏
            }else if (orientation >=306 && orientation <= 360 ) {
                rotate = 1; // 正竖屏
            }else if (orientation >=58 && orientation <= 124 ) {
                rotate = 3; // 正横屏
            }else if (orientation >=237 && orientation <= 305 ) {
                rotate = 4; // 倒横屏
            }else {
                rotate = 1; // 默认正竖屏
            }
            System.out.println("屏幕旋转角度监控：：" + rotate);
        }

    }*/

}