package com.handset.serialportsensor.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
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 ConeSettingActivity extends BaseActivity implements SurfaceContract.ISerialView {
    private static final String TAG = "HANDSET-JE002-EX";

    private Integer baudRate;
    private String sensorId;
    boolean eggNoRes = false, coneNoRes = false, coneUsedTimesRes = false, eggTypeRes = false;

    private AlertDialog settingsDialog;
    private AlertDialog getSettingsDialog;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cone_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();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (im != null) {
            View view = getCurrentFocus();
            if (view != null) {
                im.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

    private void initView() {
        initTitle();
    }

    public void onClickBtnSave(View view) {
        String value = ((EditText) (findViewById(R.id.et_egg_num))).getText().toString();
        String value2 = ((EditText) (findViewById(R.id.et_cone_num))).getText().toString();
        String value3 = ((EditText) (findViewById(R.id.et_use_num))).getText().toString();
        String value4 = ((EditText) (findViewById(R.id.et_egg_type))).getText().toString();

        if(TextUtils.isEmpty(value) && TextUtils.isEmpty(value2) &&TextUtils.isEmpty(value3) && TextUtils.isEmpty(value4)) {
            ToastUtils.showShort(getString(R.string.input_empty));
        } else {
            showSettingDialog();
            new Thread(
                    () -> {
                        Looper.prepare();
                        new Handler().postDelayed(() -> mPresenter.open(baudRate), (500));
                        Looper.loop();
                    }
            ).start();
            handler.sendEmptyMessageDelayed(Constant.Command.COMMAND_32, (3500));
            handler.sendEmptyMessageDelayed(Constant.Command.COMMAND_36, (3700));
            handler.sendEmptyMessageDelayed(Constant.Command.COMMAND_3A, (3800));
            handler.sendEmptyMessageDelayed(Constant.Command.COMMAND_40, (3900));
            handler.sendEmptyMessageDelayed(Constant.READ_TIME_OUT, (10000));
        }
    }

    private void initTitle() {
        ImageView ivBack = findViewById(R.id.title_back);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener((View view) -> finish());
        TextView tvTitle = findViewById(R.id.title_text);
        tvTitle.setText(R.string.cone_info_title);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == Constant.Command.COMMAND_32) {//弹号设置
                String value = ((EditText) (findViewById(R.id.et_egg_num))).getText().toString();
                if (!TextUtils.isEmpty(value)) {
                    Log.i(TAG, "egg no set: sensorId: " + sensorId);
                    StringBuilder sb = new StringBuilder(sensorId);
                    //String length = "0".concat(String.valueOf(value.length()));
                    String length = "0".concat(Integer.toHexString(value.length()));
                    String length2 = length.substring(length.length() - 2);
                    //Log.i(TAG, "egg no set: length2: " + length2);
                    sb.append("00").append("32").append(length2).append(ByteUtils.strToHexStr(value));
                    String cooked = "DDDD".concat(sb.toString().concat(CRCUtils.genCrc(sb.toString())));
                    Log.i(TAG, "egg no set: cooked: " + cooked);
                    Log.i(TAG, "egg no set: cooked 2: " + Arrays.toString(cooked.getBytes()));
                    mPresenter.write(cooked);
                }
            } else if (msg.what == Constant.Command.COMMAND_36) {//筒号设置
                String value = ((EditText) (findViewById(R.id.et_cone_num))).getText().toString();
                if (!TextUtils.isEmpty(value)) {
                    StringBuilder sb = new StringBuilder(sensorId);
                    //String length = "0".concat(String.valueOf(value.length()));
                    String length = "0".concat(Integer.toHexString(value.length()));
                    String length2 = length.substring(length.length() - 2);
                    sb.append("00").append("36").append(length2).append(ByteUtils.strToHexStr(value));

                    String cooked = "DDDD".concat(sb.toString().concat(CRCUtils.genCrc(sb.toString())));
                    Log.i(TAG, "cone no set: cooked: " + cooked);

                    mPresenter.write(cooked);
                }
            } else if (msg.what == Constant.Command.COMMAND_3A) {//弹筒使用次数设置
                String value = ((EditText) (findViewById(R.id.et_use_num))).getText().toString();
                if (!TextUtils.isEmpty(value)) {
                    StringBuilder sb = new StringBuilder(sensorId);
                    String length = "0".concat(String.valueOf(value.length()));
                    String length2 = length.substring(length.length() - 2);
                    sb.append("00").append("3A").append(length2).append(ByteUtils.strToHexStr(value));

                    String cooked = "DDDD".concat(sb.toString().concat(CRCUtils.genCrc(sb.toString())));
                    Log.i(TAG, "cone used times set: cooked: " + cooked);

                    mPresenter.write(cooked);
                }
            } else if (msg.what == Constant.Command.COMMAND_40) { // 弹型
                String value = ((EditText) (findViewById(R.id.et_egg_type))).getText().toString();
                if (!TextUtils.isEmpty(value)) {
                    StringBuilder sb = new StringBuilder(sensorId);
                    String length = "0".concat(Integer.toHexString(value.length()));
                    String length2 = length.substring(length.length() - 2);
                    sb.append("00").append("40").append(length2).append(ByteUtils.strToHexStr(value));
                    String cooked = "DDDD".concat(sb.toString().concat(CRCUtils.genCrc(sb.toString())));
                    Log.i(TAG, "egg type set: cooked: " + cooked);

                    mPresenter.write(cooked);
                }
            } else if (msg.what == Constant.READ_TIME_OUT) {
                if (eggNoRes || coneNoRes || coneUsedTimesRes || eggTypeRes) {
                    /*ToastUtils.showShort(R.string.setting_success);*/
                    runOnUiThread(() -> {
                        disMissLoadingDialog(settingsDialog);
                        if (!(getSettingsDialog != null && getSettingsDialog.isShowing())) {
                            getSettingsDialog = ToastHelper.showSubmitDialog(
                                    getString(R.string.set_cone_info_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),
                                    (ConeSettingActivity.this),
                                    (View view) -> finish()
                            );
                        }
                    });
                } else {
                    runOnUiThread(() -> {
                        disMissLoadingDialog(settingsDialog);
                        if (!(getSettingsDialog != null && getSettingsDialog.isShowing())) {
                            getSettingsDialog = ToastHelper.showSubmitDialog(
                                    getString(R.string.set_cone_info_failed),
                                    R.mipmap.img_cross,
                                    getString(R.string.go_back_init_screen_content),
                                    getResources().getColor(R.color.blue_button_bg),
                                    getString(R.string.btn_ensure),
                                    (ConeSettingActivity.this),
                                    (View view) -> finish()
                            );
                        }
                    });
                }

                /*findViewById(R.id.btn_save).setEnabled(true);
                findViewById(R.id.btn_save).setBackgroundResource(R.drawable.bg_start_btn_new);
                ((Button) findViewById(R.id.btn_save)).setText(R.string.save_settings);*/
            }
        }
    };

    @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(TAG, "ConeSettingActivity, onSerialData: " + message);
            byte[] bytes = ByteUtils.hexStrToBytes(message);

            if ((bytes[6] & 0xff) == 0x0 && (bytes[7] & 0xff) == Constant.Command.COMMAND_33) { //egg no
                eggNoRes = ((bytes[9] & 0xff) == 0xff);
            } else if ((bytes[6] & 0xff) == 0x0 && (bytes[7] & 0xff) == Constant.Command.COMMAND_37) { //cone no
                coneNoRes = (bytes[9] & 0xff) == 0xff;
            } else if ((bytes[6] & 0xff) == 0x0 && (bytes[7] & 0xff) == Constant.Command.COMMAND_3B) { //cone used times
                coneUsedTimesRes = (bytes[9] & 0xff) == 0xff;
            } else if ((bytes[6] & 0xff) == 0x0 && (bytes[7] & 0xff) == Constant.Command.COMMAND_41) { //egg type
                eggTypeRes = (bytes[9] & 0xff) == 0xff;
            }
        }
    }

    @Override
    public void onSerialError(Integer errorCode) {

    }

    private void showSettingDialog() {
        runOnUiThread(() -> settingsDialog = ToastHelper.showTipDialog((ConeSettingActivity.this), R.mipmap.ic_setting, R.string.write_info_now_tips));
    }
}
