package com.handset.serialportsensor.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;

import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handset.serialportlib.ByteUtils;
import com.handset.serialportlib.CRCUtils;
import com.handset.serialportsensor.R;
import com.handset.serialportsensor.bean.RawData;
import com.handset.serialportsensor.constant.Constant;
import com.handset.serialportsensor.presenter.SurfaceContract;
import com.handset.serialportsensor.presenter.SurfacePresenter;
import com.handset.serialportsensor.utils.ToastHelper;

import java.util.Arrays;

public class BaudRateSettingActivity extends BaseActivity implements View.OnClickListener, SurfaceContract.ISerialView {
    private final String logTag = "HANDSET-JE002-EX";

    private TextView tvBr9600;
    private TextView tvBr19200;
    private TextView tvNum3;
    private ImageView ivBr9600;
    private ImageView ivBr19200;
    private ImageView ivBr38400;

    private byte baudByte = 0x01;
    private Integer baudRate;
    private String sensorId;

    private AlertDialog baudSettingsDialog;

    private SurfacePresenter mPresenter = new SurfacePresenter((this));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baudrate_setting);
        Intent intent = getIntent();
        if (intent != null) {
            baudRate = intent.getIntExtra(Constant.BAUD_RATE, (38400));
            sensorId = intent.getStringExtra(Constant.SENSOR_ID);
        }
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mPresenter.close();
        super.onDestroy();
    }

    private void initView() {
        TextView tvTitle = findViewById(R.id.title_text);
        ImageView ivBack = findViewById(R.id.title_back);
        TextView tvConfirm = findViewById(R.id.tv_confirm);
        RelativeLayout rlNum1 = findViewById(R.id.rl_br_9600);
        RelativeLayout rlNum2 = findViewById(R.id.rl_br_19200);
        RelativeLayout rlNum3 = findViewById(R.id.rl_br_38400);
        tvBr9600 = findViewById(R.id.tv_br_9600);
        tvBr19200 = findViewById(R.id.tv_br_19200);
        tvNum3 = findViewById(R.id.tv_br_38400);
        ivBr9600 = findViewById(R.id.iv_br_9600);
        ivBr19200 = findViewById(R.id.iv_br_19200);
        ivBr38400 = findViewById(R.id.iv_br_38400);
        tvTitle.setText(R.string.baud_rate_setting);
        ivBack.setVisibility(View.VISIBLE);
        tvConfirm.setVisibility(View.VISIBLE);
        tvConfirm.setText(R.string.confirm);
        tvBr9600.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        ivBr9600.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        tvConfirm.setOnClickListener(this);
        rlNum1.setOnClickListener(this);
        rlNum2.setOnClickListener(this);
        rlNum3.setOnClickListener(this);
        if (baudRate == 38400) {
            clickId(R.id.rl_br_38400);
        } else if (baudRate == 19200) {
            clickId(R.id.rl_br_19200);
        } else if (baudRate == 9600) {
            clickId(R.id.rl_br_9600);
        }
    }

    @Override
    public void onClick(View view) {
        clickId(view.getId());
    }

    private void clickId(int id) {
        switch (id) {
            case R.id.title_back:
                this.finish();
                break;
            case R.id.tv_confirm:
                if (ivBr9600.getVisibility() == View.VISIBLE) {
                    baudByte = 0x01;
                } else if (ivBr19200.getVisibility() == View.VISIBLE) {
                    baudByte = 0x02;
                } else {
                    baudByte = 0x03;
                }
                setBaudRate();
                break;
            case R.id.rl_br_9600:
                tvBr9600.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                tvBr19200.setTextColor(getResources().getColor(R.color.text_general_color));
                tvNum3.setTextColor(getResources().getColor(R.color.text_general_color));
                ivBr9600.setVisibility(View.VISIBLE);
                ivBr19200.setVisibility(View.GONE);
                ivBr38400.setVisibility(View.GONE);
                break;
            case R.id.rl_br_19200:
                tvBr9600.setTextColor(getResources().getColor(R.color.text_general_color));
                tvBr19200.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                tvNum3.setTextColor(getResources().getColor(R.color.text_general_color));
                ivBr9600.setVisibility(View.GONE);
                ivBr19200.setVisibility(View.VISIBLE);
                ivBr38400.setVisibility(View.GONE);
                break;
            case R.id.rl_br_38400:
                tvBr9600.setTextColor(getResources().getColor(R.color.text_general_color));
                tvBr19200.setTextColor(getResources().getColor(R.color.text_general_color));
                tvNum3.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                ivBr9600.setVisibility(View.GONE);
                ivBr19200.setVisibility(View.GONE);
                ivBr38400.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void setBaudRate() {
        Log.i(logTag, ("Setting BaudRate：" + baudRate));
        showSettingDialog();

        new Thread(
                () -> {
                    Looper.prepare();
                    new Handler().postDelayed(() -> mPresenter.open(baudRate), (300));
                    Looper.loop();
                }
        ).start();

        handler.sendEmptyMessageDelayed(Constant.Command.COMMAND_3C, (3300));
        new Handler().postDelayed(() -> {
            if (baudSettingsDialog != null && baudSettingsDialog.isShowing()) {
                baudSettingsDialog.dismiss();
                setBaudFailed();
            }
        }, (10000));
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == Constant.Command.COMMAND_3C) {//波特率设置
                Log.i(logTag, ("baud rate set: sensorId: " + sensorId));
                StringBuilder sb = new StringBuilder(sensorId);
                sb.append("00").append("3C").append("01").append("0".concat(String.valueOf(baudByte)));
                String cooked = "DDDD".concat(sb.toString().concat(CRCUtils.genCrc(sb.toString())));
                Log.i(logTag, "baud rate set: cooked: " + cooked);
                Log.i(logTag, "baud rate set: cooked 2: " + Arrays.toString(cooked.getBytes()));
                mPresenter.write(cooked);
            }
        }
    };

    //正在设置波特率
    private void showSettingDialog() {
        runOnUiThread(() -> baudSettingsDialog = ToastHelper.showTipDialog((BaudRateSettingActivity.this), R.mipmap.ic_setting, R.string.set_baud_rate_now_tips));
    }

    @Override
    public void onSerialOpen(boolean isOpen) {

    }

    @Override
    public void onSerialBaudRate(Integer baudRate) {

    }

    @Override
    public void onSerialData(RawData rawData) {
        if (rawData.getItemType() == RawData.TYPE_RECEIVE) {
            String message = rawData.getMessage();
            Log.i(logTag, ("BaudRateSettingActivity, onSerialData: " + message));
            byte[] bytes = ByteUtils.hexStrToBytes(message);
            if ((bytes[6] & 0xff) == 0x0 && (bytes[7] & 0xff) == Constant.Command.COMMAND_3D) {
                mPresenter.close();
                if (baudSettingsDialog != null && baudSettingsDialog.isShowing()) {
                    baudSettingsDialog.dismiss();
                }
                setBaudSuccess();
            }
        }
    }

    @Override
    public void onSerialError(Integer errorCode) {

    }

    //波特率设置成功
    private void setBaudSuccess() {
        runOnUiThread(() -> {
            disMissLoadingDialog(baudSettingsDialog);
            ToastHelper.showSubmitDialog(
                    getString(R.string.set_baud_rate_success),
                    R.mipmap.img_right,
                    getString(R.string.go_back_init_screen_content),
                    getResources().getColor(R.color.blue_button_bg),
                    getString(R.string.btn_ensure), BaudRateSettingActivity.this,
                    (View view) -> {
                        finish();
                        Intent intent = new Intent((BaudRateSettingActivity.this), Main2Activity.class);
                        intent.putExtra(Constant.SENSOR_ID, sensorId);
                        startActivity(intent);
                    });
        });

    }

    //波特率设置失败
    private void setBaudFailed() {
        runOnUiThread(() -> {
            disMissLoadingDialog(baudSettingsDialog);
            ToastHelper.showSubmitDialog(
                    getString(R.string.set_baud_rate_failed),
                    R.mipmap.img_cross,
                    getString(R.string.go_back_init_screen_content),
                    getResources().getColor(R.color.button),
                    getString(R.string.btn_ensure),
                    (BaudRateSettingActivity.this),
                    (View view) -> finish()
            );
        });
    }
}
