package h.com.newserialapp.activity.MIAFREDESFireActivity.ApplicationLevel;

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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
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.FontEditText;
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 ValueFile extends BaseActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    private FontTextView tvValue, tvBack, tvStatus;
    private FontEditText etFileId, etComSet, etComSet02, etComSet03, etAccessRight, etLowerLimit, etUperLimit, etValue, etFileId02, etFileId03, etValue03;
    private Button btCreateValueFile, btGetValue, btCredit, btDebit, btCommitTransaction, btAbsortTransaction, btLimitCredit;
    private String[] limitArray;
    private Spinner limitSpinner;

    private String tempCommand;

    private Reader reader;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    if (!tempCommand.substring(0, 2).equals("F0")) {
                        tvValue.setText(tempCommand.substring(8, tempCommand.length() - 2));
                    }
                    break;
                case 102:

                    break;
            }
            return false;
        }
    });


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_value_file);
        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");
        limitArray = getResources().getStringArray(R.array.item02);
        limitSpinner = findViewById(R.id.spinner_limit_credit);
        limitSpinner.setAdapter(new ArrayAdapter<>(this, R.layout.spinner_default_item, limitArray));
        tvValue = findViewById(R.id.tv_value);
        tvBack = findViewById(R.id.tv_back);
        tvStatus = findViewById(R.id.tv_status_bar);
        etFileId = findViewById(R.id.et_file_id);
        etComSet = findViewById(R.id.et_comset);
        etComSet02= findViewById(R.id.et_comset2);
        etComSet03= findViewById(R.id.et_comset3);
        etAccessRight = findViewById(R.id.et_access_right);
        etLowerLimit = findViewById(R.id.et_lower_limit);
        etUperLimit = findViewById(R.id.et_uper_limit);
        etValue = findViewById(R.id.et_value);
        etFileId02 = findViewById(R.id.et_file_id_2);
        etFileId03 = findViewById(R.id.et_file_id_3);
        etValue03 = findViewById(R.id.et_value_02);
        btCreateValueFile = findViewById(R.id.bt_create_value_file);
        btGetValue = findViewById(R.id.bt_get_value);
        btCredit = findViewById(R.id.bt_credit);
        btDebit = findViewById(R.id.bt_debit);
        btCommitTransaction = findViewById(R.id.bt_commit_transaction);
        btAbsortTransaction = findViewById(R.id.bt_absort_transaction);
        btLimitCredit = findViewById(R.id.bt_limit_credit);
        btCreateValueFile.setOnClickListener(this);
        btGetValue.setOnClickListener(this);
        btCredit.setOnClickListener(this);
        btDebit.setOnClickListener(this);
        btCommitTransaction.setOnClickListener(this);
        btAbsortTransaction.setOnClickListener(this);
        btLimitCredit.setOnClickListener(this);
        tvBack.setOnClickListener(this);
        btCreateValueFile.setTypeface(typeface);
        btGetValue.setTypeface(typeface);
        btCredit.setTypeface(typeface);
        btDebit.setTypeface(typeface);
        btCommitTransaction.setTypeface(typeface);
        btAbsortTransaction.setTypeface(typeface);
        btLimitCredit.setTypeface(typeface);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back: {
                finish();
                break;
            }
            case R.id.bt_create_value_file: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etFileId.getText().toString()) || Tools.isNull(etComSet.getText().toString())) {
                    Tools.showToast(this, "Parameter File ID, ComSet is not null");
                    return;
                }
                byte[] AccessRight = Tools.toByteArray(etAccessRight.getText().toString());
                if (AccessRight == null || AccessRight.length != 2) {
                    Tools.showToast(this, "Parameter AccessRight must be 2 bytes");
                    return;
                }
                byte[] LowerLimit = Tools.toByteArray(etLowerLimit.getText().toString());
                byte[] UpperLimit = Tools.toByteArray(etUperLimit.getText().toString());
                byte[] Value = Tools.toByteArray(etValue.getText().toString());
                if (LowerLimit == null || LowerLimit.length != 4 ||
                        UpperLimit == null || UpperLimit.length != 4 ||
                        Value == null || Value.length != 4) {
                    Tools.showToast(this, "Parameter LowerLimit, UpperLimit, Value must be 4 bytes");
                    return;
                }
                reader.DESCreateValueFile(Tools.toByte(etFileId.getText().toString()), Tools.toByte(etComSet.getText().toString()), AccessRight, LowerLimit, UpperLimit, Value, Tools.toByte(limitValue));
                break;
            }
            case R.id.bt_get_value: {
                byte[] Value = new byte[4];

                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etFileId02.getText().toString()) || Tools.isNull(etComSet02.getText().toString())) {
                    Tools.showToast(this, "Parameter File ID, ComSet is not null");
                    return;
                }
                int result = reader.DESEV1GetValue(Tools.toByte(etFileId02.getText().toString()), Tools.toByte(etComSet02.getText().toString()), Value);
                if (result == 0) {
                    tvValue.setText(Tools.toHexString(Value, 4));
                } else {
                    tvValue.setText("");
                }
                break;
            }
            case R.id.bt_credit: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etFileId03.getText().toString()) || Tools.isNull(etComSet03.getText().toString())) {
                    Tools.showToast(this, "Parameter File ID, ComSet is not null");
                    return;
                }
                byte[] Value = Tools.toByteArray(etValue03.getText().toString());
                if (Value == null || Value.length != 4) {
                    Tools.showToast(this, "Parameter Value must be 4 byte");
                    return;
                }
                reader.DESEV1_CREDIT(Tools.toByte(etFileId03.getText().toString()), Tools.toByte(etComSet03.getText().toString()), Value);
                break;
            }
            case R.id.bt_debit: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etFileId03.getText().toString()) || Tools.isNull(etComSet03.getText().toString())) {
                    Tools.showToast(this, "Parameter File ID, ComSet is not null");
                    return;
                }
                byte[] Value = Tools.toByteArray(etValue03.getText().toString());
                if (Value == null || Value.length != 4) {
                    Tools.showToast(this, "Parameter Value must be 4 byte");
                    return;
                }
                reader.DESEV1_DEBIT(Tools.toByte(etFileId03.getText().toString()), Tools.toByte(etComSet03.getText().toString()), Value);
                break;
            }
            case R.id.bt_commit_transaction: {
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                reader.DES_CommitTransaction();
                break;
            }
            case R.id.bt_absort_transaction: {
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                reader.DES_AbortTransaction();
                break;
            }
            case R.id.bt_limit_credit: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etFileId03.getText().toString()) || Tools.isNull(etComSet03.getText().toString())) {
                    Tools.showToast(this, "Parameter File ID, ComSet is not null");
                    return;
                }
                byte[] Value = Tools.toByteArray(etValue03.getText().toString());
                if (Value == null || Value.length != 4) {
                    Tools.showToast(this, "Parameter Value must be 4 bytes");
                    return;
                }
                reader.DESEV1_LIMITEDCREDIT(Tools.toByte(etFileId.getText().toString()), Tools.toByte(etComSet.getText().toString()), Value);
                break;
            }
        }

    }

    private String limitValue = "00";

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.spinner_limit_credit:
                limitValue = limitArray[position];
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

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