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.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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;

/**
 * Created by zy on 2019/2/23.
 */

public class ChangeSensorIdSettingsActivity extends BaseActivity implements SurfaceContract.ISerialView {
    private static final String logTag = "HANDSET-JE002-EX";

    private String sensorId;
    private Integer baudRate;
    private EditText etSensorId;
    private SurfacePresenter mPresenter = new SurfacePresenter((this));

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_sensor_id_setings);
        Intent intent = getIntent();
        if (intent != null) {
            sensorId = intent.getStringExtra(Constant.SENSOR_ID);
            baudRate = intent.getIntExtra(Constant.BAUD_RATE, (38400));
        }
        etSensorId = findViewById(R.id.et_sensor_id);
        findViewById(R.id.btn_save).setOnClickListener((View v) -> save());
        initTitle();
        etSensorId.setText(sensorIdToInt(sensorId));
    }

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

    private String sensorIdToInt(String sensorId) {
        byte[] bytes = ByteUtils.hexStrToBytes(sensorId);
        Log.i(logTag, "sensorId hexStrToBytes: " + Arrays.toString(bytes));
        int no = ((bytes[0] & 0xff) * 100 + (bytes[1] & 0xff)) * 10000 + ((bytes[2] & 0xff) << 8) + (bytes[3] & 0xff);
        String s = "00000000".concat(String.valueOf(no));
        return s.substring(s.length() - 8);
    }

    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.id_setting);
    }

    private void save() {
        String sensorId = etSensorId.getText().toString();
        if (TextUtils.isEmpty(sensorId) || sensorId.length() != 8) {
            Toast.makeText((this), R.string.id_must_8bits_tip, Toast.LENGTH_SHORT).show();
        } else {
            boolean tagAccept = true;
            for (int i = 0; i < 8; i++) {
                char a = sensorId.charAt(i);
                if (!from0to9(a)) {
                    Toast.makeText((this), R.string.id_must_8bits_tip, Toast.LENGTH_SHORT).show();
                    tagAccept = false;
                    break;
                }
            }
            if (tagAccept) {
                showSettingDialog();
                new Thread(
                        () -> {
                            Looper.prepare();
                            new Handler().postDelayed(() -> mPresenter.open(baudRate), (500));
                            Looper.loop();
                        }
                ).start();

                handler.sendEmptyMessageDelayed(Constant.Command.COMMAND_50, (3500));
            }
        }
    }

    private AlertDialog settingsDialog;

    private void showSettingDialog() {
        runOnUiThread(() -> {
                    settingsDialog = ToastHelper.showTipDialog((ChangeSensorIdSettingsActivity.this), R.mipmap.ic_setting, R.string.id_setting_tip);
                    //disMissDialogDelay(settingsDialog, (10000));
                    dismissSettingDialogDelay();
                }
        );
    }

    private Handler dismissHandler = new Handler();
    private Runnable dismissRunnable;
    private void dismissSettingDialogDelay() {
        dismissRunnable = () -> {
            dismissDialogD(settingsDialog);
            runOnUiThread(() -> Toast.makeText((ChangeSensorIdSettingsActivity.this), R.string.sensor_id_set_fail, Toast.LENGTH_SHORT).show());
        };
        dismissHandler.postDelayed(dismissRunnable, (10000));
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == Constant.Command.COMMAND_50) {//设置传感器ID
                StringBuilder sb = new StringBuilder(sensorId);
                byte[] bytes = ByteUtils.getByte4Id(etSensorId.getText().toString());
                String hexString = ByteUtils.bytesToHexStr(bytes);
                Log.i(logTag, "sensor no set: sensor prior: " + Arrays.toString(bytes));
                Log.i(logTag, "sensor no set: hexString: " + hexString);

                sb.append("00").append("50").append("04").append(hexString);
                String cooked = "DDDD".concat(sb.toString().concat(CRCUtils.genCrc(sb.toString())));
                Log.i(logTag, "sensor no set: cooked: " + cooked);
                Log.i(logTag, "sensor no set: cooked 2: " + Arrays.toString(cooked.getBytes()));
                mPresenter.write(cooked);
            }
        }
    };

    private boolean from0to9(char c) {
        return (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9');
    }

    @Override
    public void onSerialOpen(boolean isOpen) {

    }

    @Override
    public void onSerialBaudRate(Integer baudRate) {

    }

    @Override
    public void onSerialData(RawData rawData) {
        if (rawData.getItemType() == RawData.TYPE_RECEIVE) {
            Log.i(logTag, "ChangeSensorIdSettingsActivity, onSerialData: " + rawData.getMessage());
            byte[] bytes = ByteUtils.hexStrToBytes(rawData.getMessage());
            Log.i(logTag, "ChangeSensorIdSettingsActivity, onSerialData 2: " + Arrays.toString(bytes));
            if (bytes.length >= 8) {
                if ((bytes[6] & 0xff) == 0 && (bytes[7] & 0xff) == Constant.Command.COMMAND_51) {
                    Log.i(logTag, "ChangeSensorIdSettingsActivity, onSerialData, 0x51 feedback: " + rawData.getMessage());
                    mPresenter.close();
                    dismissDialog(settingsDialog);
                    dismissHandler.removeCallbacks(dismissRunnable);
                    runOnUiThread(() -> Toast.makeText((ChangeSensorIdSettingsActivity.this), R.string.sensor_id_set_success, Toast.LENGTH_SHORT).show());
                    finish();
                    Intent intent = new Intent((ChangeSensorIdSettingsActivity.this), Main2Activity.class);
                    intent.putExtra(Constant.SENSOR_ID, sensorId);
                    startActivity(intent);
                } else {
                    runOnUiThread(() -> Toast.makeText((ChangeSensorIdSettingsActivity.this), R.string.sensor_id_set_fail, Toast.LENGTH_SHORT).show());
                }
            }
        }
    }

    @Override
    public void onSerialError(Integer errorCode) {

    }
}
