package h.com.newserialapp.activity.MIAFREDESFireActivity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import h.com.newserialapp.R;
import h.com.newserialapp.activity.BaseActivity;
import h.com.newserialapp.util.ToastUtil;
import h.com.newserialapp.util.Tools;
import h.com.newserialapp.views.FontTextView;
import h.com.serialportapi.comn.CommPacket;
import h.com.serialportapi.comn.Reader;
import h.com.serialportapi.comn.SerialPortManager;
import h.com.serialportapi.comn.SerialReadThread;
import h.com.serialportapi.comn.message.IMessage;

/**
 * Created by hxd on 2018/12/8.
 */

public class KeyCommandsActivity extends BaseActivity implements View.OnClickListener {
    private EditText etKeyNumber, etKey, etNewKeySetting, etKeyNumber02, etKeySetting, etOriginalKey, etNewkey;
    private FontTextView tvKeyVersion, tvKeySetting, tvBack, tvStatus;
    private Button btGetKeyVersion, btAuthenticate, btGetKeySetting, btChangeKeySetting, btChangeKey;
    private String receiveCommand;// serial port receive command

    private Reader reader;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    if (receiveCommand.substring(0, 2).equals("50")) {
                        tvKeyVersion.setText(receiveCommand.substring(8, receiveCommand.length() - 2));
                    }
                    break;
                case 102:
                    if (receiveCommand.substring(0, 2).equals("50")) {
                        tvKeySetting.setText(receiveCommand.substring(10, receiveCommand.length() - 2));
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_key_commands);
        bindView();

        reader = SerialPortManager.instance().reader;
        if (reader == null) {
            Toast.makeText(this, "Please open the serial port first.", Toast.LENGTH_LONG).show();
        } else {
            reader.setLisenter(true);
        }
    }

    void bindView() {
        Typeface typeface = Typeface.createFromAsset(this.getAssets(), "fonts/Eurostile LT Demi.ttf");
        etKeyNumber = findViewById(R.id.et_key_number);
        etKey = findViewById(R.id.et_key);
        etNewKeySetting = findViewById(R.id.et_new_key_setting);
        etKeyNumber02 = findViewById(R.id.et_key_number_2);
        etKeySetting = findViewById(R.id.et_key_setting);
        etOriginalKey = findViewById(R.id.et_original_key);
        etNewkey = findViewById(R.id.et_new_key);
        tvKeyVersion = findViewById(R.id.tv_key_version);
        tvKeySetting = findViewById(R.id.tv_key_setting);
        tvBack = findViewById(R.id.tv_back);
        tvStatus = findViewById(R.id.tv_status_bar);
        btGetKeyVersion = findViewById(R.id.bt_get_key_version);
        btAuthenticate = findViewById(R.id.bt_authenticate);
        btGetKeySetting = findViewById(R.id.bt_get_key_setting);
        btChangeKeySetting = findViewById(R.id.bt_change_key_setting);
        btChangeKey = findViewById(R.id.bt_change_key);
        tvBack.setOnClickListener(this);
        btGetKeyVersion.setOnClickListener(this);
        btAuthenticate.setOnClickListener(this);
        btGetKeySetting.setOnClickListener(this);
        btChangeKeySetting.setOnClickListener(this);
        btChangeKey.setOnClickListener(this);
        btGetKeyVersion.setTypeface(typeface);
        btAuthenticate.setTypeface(typeface);
        btGetKeySetting.setTypeface(typeface);
        btChangeKeySetting.setTypeface(typeface);
        btChangeKey.setTypeface(typeface);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_get_key_version: {
                byte[] pKeyVersion = new byte[1];

                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etKeyNumber.getText().toString())) {
                    Tools.showToast(this, "Key Number is not null");
                    return;
                }
                int result = reader.DESGetKeyVersion(Tools.toByte(etKeyNumber.getText().toString()), pKeyVersion);
                if (result == 0) {
                    tvKeyVersion.setText(Tools.toHexString(pKeyVersion, 1));
                } else {
                    tvKeyVersion.setText("");
                }
                break;
            }
            case R.id.bt_authenticate: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etKeyNumber.getText().toString())) {
                    Tools.showToast(this, "Key Number is not null");
                    return;
                }
                byte[] pKey = Tools.toByteArray(etKey.getText().toString());
                if (pKey == null || pKey.length != 16) {
                    Tools.showToast(this, "Key must be 16 bytes");
                    return;
                }
                reader.DESAuthenticate(Tools.toByte(etKeyNumber.getText().toString()), pKey);
                break;
            }
            case R.id.bt_get_key_setting: {
                byte[] pKeySetting = new byte[1];
                byte[] pMaxKeyNum = new byte[1];

                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                int result = reader.DESGetKeySetting(pKeySetting, pMaxKeyNum);
                if (result == 0) {
                    tvKeySetting.setText(Tools.toHexString(pKeySetting, 1));
                } else {
                    tvKeySetting.setText("");
                }
                break;
            }
            case R.id.bt_change_key_setting: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etNewKeySetting.getText().toString())) {
                    Tools.showToast(this, "New Key Setting is not null");
                    return;
                }
                reader.DESChangKeySetting(Tools.toByte(etNewKeySetting.getText().toString()));
                break;
            }
            case R.id.bt_change_key: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etKeyNumber02.getText().toString()) || Tools.isNull(etKeySetting.getText().toString())) {
                    Tools.showToast(this, "Key Number and Key Setting is not null");
                    return;
                }
                byte[] oldKey = Tools.toByteArray(etOriginalKey.getText().toString());
                byte[] newKey = Tools.toByteArray(etNewkey.getText().toString());
                if (oldKey == null || oldKey.length != 16 || newKey == null || newKey.length != 16) {
                    Tools.showToast(this, "The original Key and new key must be 16 bytes");
                    return;
                }
                reader.DESChangKey(Tools.toByte(etKeyNumber02.getText().toString()), Tools.toByte(etKeySetting.getText().toString()), newKey, oldKey);
                break;
            }
            case R.id.tv_back: {
                finish();
                break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(IMessage message) {
        // 收到时间，刷新界面
        tvStatus.setText(message.getMessage());
    }

}
