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.Button;
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 RecordFile extends BaseActivity implements View.OnClickListener {

    private FontEditText etFileId, etComSet, etComSet02, etComSet03, etAccessRight, etFileSize, etRecordNumber, etFileId02, etRecordNo, etRecordNumber02, etFileId03, etAddress, etWriteRecord;
    private FontTextView tvReadRecord, tvBack, tvStatus;
    private Button btCreateLinearRecordFile, btCreateCyclicRecordFile, btClearRecordFile, btReadRecord, btWriteRecord;
    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")) {
                        tvReadRecord.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_record_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");
        etFileId = findViewById(R.id.et_file_id);
        etComSet = findViewById(R.id.et_comset);
        etAccessRight = findViewById(R.id.et_access_right);
        etFileSize = findViewById(R.id.et_file_size);
        etRecordNumber = findViewById(R.id.et_record_number);
        etFileId02 = findViewById(R.id.et_file_id_2);
        etComSet02 = findViewById(R.id.et_comset2);
        etRecordNo = findViewById(R.id.et_record_no);
        etRecordNumber02 = findViewById(R.id.et_record_number_2);
        etFileId03 = findViewById(R.id.et_file_id_3);
        etComSet03 = findViewById(R.id.et_comset3);
        etAddress = findViewById(R.id.et_address);
        etWriteRecord = findViewById(R.id.et_write_record);
        tvReadRecord = findViewById(R.id.tv_read_record);
        tvBack = findViewById(R.id.tv_back);
        tvStatus = findViewById(R.id.tv_status_bar);
        btCreateLinearRecordFile = findViewById(R.id.bt_create_linear_record_file);
        btCreateCyclicRecordFile = findViewById(R.id.bt_create_cyclic_record_file);
        btClearRecordFile = findViewById(R.id.bt_clear_record_file);
        btReadRecord = findViewById(R.id.bt_read_record);
        btWriteRecord = findViewById(R.id.bt_write_record);
        tvBack.setOnClickListener(this);
        btCreateLinearRecordFile.setOnClickListener(this);
        btCreateCyclicRecordFile.setOnClickListener(this);
        btClearRecordFile.setOnClickListener(this);
        btReadRecord.setOnClickListener(this);
        btWriteRecord.setOnClickListener(this);
        btCreateLinearRecordFile.setTypeface(typeface);
        btCreateCyclicRecordFile.setTypeface(typeface);
        btClearRecordFile.setTypeface(typeface);
        btReadRecord.setTypeface(typeface);
        btWriteRecord.setTypeface(typeface);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_create_linear_record_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());
                byte[] FileSize = Tools.toByteArray(etFileSize.getText().toString());
                byte[] RecordsNum = Tools.toByteArray(etRecordNumber.getText().toString());
                if (AccessRight == null || AccessRight.length != 2 || FileSize == null || FileSize.length != 2 || RecordsNum == null || RecordsNum.length != 2) {
                    Tools.showToast(this, "Parameter AccessRight, FileSize, Records Number must be 2 bytes");
                    return;
                }
                reader.DESCreateLinearRecordFile(Tools.toByte(etFileId.getText().toString()), Tools.toByte(etComSet.getText().toString()), AccessRight, FileSize, RecordsNum);
                break;
            }
            case R.id.bt_create_cyclic_record_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());
                byte[] FileSize = Tools.toByteArray(etFileSize.getText().toString());
                byte[] RecordsNum = Tools.toByteArray(etRecordNumber.getText().toString());
                if (AccessRight == null || AccessRight.length != 2 || FileSize == null || FileSize.length != 2 || RecordsNum == null || RecordsNum.length != 2) {
                    Tools.showToast(this, "Parameter AccessRight, FileSize, Records Number must be 2 bytes");
                    return;
                }
                reader.DESCreateCyclicRecordFile(Tools.toByte(etFileId.getText().toString()), Tools.toByte(etComSet.getText().toString()), AccessRight, FileSize, RecordsNum);
                break;
            case R.id.bt_clear_record_file: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etFileId.getText().toString())) {
                    Tools.showToast(this, "Parameter File ID is not null");
                    return;
                }
                reader.DESClearRecordFile(Tools.toByte(etFileId.getText().toString()));
                break;
            }
            case R.id.bt_read_record: {
                byte[] pBuf = new byte[1024];
                int[] RcvLen = new int[1];

                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;
                }
                byte[] RecordNo = Tools.toByteArray(etRecordNo.getText().toString());
                byte[] RecordNumber = Tools.toByteArray(etRecordNumber02.getText().toString());
                if (RecordNo == null || RecordNo.length != 2 || RecordNumber == null || RecordNumber.length != 2) {
                    Tools.showToast(this, "Parameter RecordNo and Record Number must be 2 bytes");
                    return;
                }
                int result = reader.DESEV1ReadRecord(Tools.toByte(etFileId02.getText().toString()), Tools.toByte(etComSet02.getText().toString()), RecordNo, RecordNumber, pBuf, RcvLen);
                if (result == 0) {
                    tvReadRecord.setText(Tools.toHexString(pBuf, RcvLen[0]));
                } else {
                    tvReadRecord.setText("");
                }
                break;
            }
            case R.id.bt_write_record: {
                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[] RecordAddr = Tools.toByteArray(etAddress.getText().toString());
                if (RecordAddr == null || RecordAddr.length != 2) {
                    Tools.showToast(this, "Parameter Record Address must be 2 bytes");
                    return;
                }
                byte[] RecordData = Tools.toByteArray(etWriteRecord.getText().toString());
                if (RecordData == null || RecordData.length == 0) {
                    Tools.showToast(this, "Write Record Data is not null");
                    return;
                }
                byte[] Length = new byte[2];
                Length[0] = (byte)(RecordData.length >>> 8);
                Length[1] = (byte)(RecordData.length);
                reader.DESEV1WriteRecord(Tools.toByte(etFileId03.getText().toString()), Tools.toByte(etComSet03.getText().toString()), RecordAddr, Length, RecordData);
                break;
            }
            case R.id.tv_back: {
                finish();
                break;
            }
        }
    }

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