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.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

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

import h.com.newserialapp.R;
import h.com.newserialapp.SerialAPP;
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 BackupFile extends BaseActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    private FontEditText etFileId, etComSet, etComSet1, etAccessRight, etFileSize, etAddress, etLength, etWriteData;
    private FontTextView tvReadData, tvBack,tvStatus;
    private Spinner spinnerFileId;
    private Button btCreateBackupFile, btReadData, btWriteData;

    private String[] fileIds;
    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:
                    tvReadData.setText(tempCommand.substring(8, tempCommand.length() - 2));
                    break;
                case 102:
                    CommPacket.DESTransaction("9E",new SerialReadThread.ReaderListener() {
                        @Override
                        public void transmitData(String msg) {
                            Toast.makeText(BackupFile.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_backup_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);
        etComSet1= findViewById(R.id.et_comset1);
        etAccessRight = findViewById(R.id.et_access_right);
        etFileSize = findViewById(R.id.et_file_size);
        etAddress = findViewById(R.id.et_address);
        etLength = findViewById(R.id.et_length);
        etWriteData = findViewById(R.id.et_data_write);
        tvReadData = findViewById(R.id.tv_data_read);
        tvBack = findViewById(R.id.tv_back);
        tvStatus=findViewById(R.id.tv_status_bar);
        spinnerFileId = findViewById(R.id.spinner_file_id);
        btCreateBackupFile = findViewById(R.id.bt_create_backup_file);
        btWriteData = findViewById(R.id.bt_write_data);
        btReadData = findViewById(R.id.bt_read_data);
        btCreateBackupFile.setOnClickListener(this);
        btReadData.setOnClickListener(this);
        btWriteData.setOnClickListener(this);
        tvBack.setOnClickListener(this);
        spinnerFileId.setOnItemSelectedListener(this);
        fileIds = SerialAPP.getFileIds();
        if(fileIds!=null && !Tools.isNull(fileIds[0])) {
            spinnerFileId.setAdapter(new ArrayAdapter<>(this, R.layout.spinner_default_item, fileIds));
            spinnerFileId.setSelection(0);
            fileIdValue=fileIds[0];
        }

        btCreateBackupFile.setTypeface(typeface);
        btReadData.setTypeface(typeface);
        btWriteData.setTypeface(typeface);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_create_backup_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());
                if (AccessRight == null || AccessRight.length != 2 || FileSize == null || FileSize.length != 2) {
                    Tools.showToast(this, "Parameter AccessRight, FileSize must be 2 bytes");
                    return;
                }
                reader.DESCreateBackupDataFile(Tools.toByte(etFileId.getText().toString()), Tools.toByte(etComSet.getText().toString()), AccessRight, FileSize);
                break;
            }
            case R.id.bt_read_data: {
                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(fileIdValue) || Tools.isNull(etComSet1.getText().toString())) {
                    Tools.showToast(this, "Parameter File ID, ComSet is not null");
                    return;
                }
                byte[] Offset = Tools.toByteArray(etAddress.getText().toString());
                byte[] Length = Tools.toByteArray(etLength.getText().toString());
                if (Offset == null || Offset.length != 2 || Length == null || Length.length != 2) {
                    Tools.showToast(this, "Parameter Address, Length must be 2 bytes");
                    return;
                }
                int result = reader.DESEV1ReadData(Tools.toByte(fileIdValue), Tools.toByte(etComSet1.getText().toString()), Offset, Length, pBuf, RcvLen);
                if (result == 0) {
                    tvReadData.setText(Tools.toHexString(pBuf, RcvLen[0]));
                } else {
                    tvReadData.setText("-");
                }
                break;
            }
            case R.id.bt_write_data: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(fileIdValue) || Tools.isNull(etComSet1.getText().toString())) {
                    Tools.showToast(this, "Parameter File ID, ComSet is not null");
                    return;
                }
                byte[] Offset = Tools.toByteArray(etAddress.getText().toString());
                byte[] Length = Tools.toByteArray(etLength.getText().toString());
                byte[] pBuff = Tools.toByteArray(etWriteData.getText().toString());
                if (Offset == null || Offset.length != 2 || Length == null || Length.length != 2 || pBuff == null || pBuff.length == 0) {
                    Tools.showToast(this, "Parameter Address, Length must be 2 bytes, and WriteData is not null");
                    return;
                }
                reader.DESEV1WriteData(Tools.toByte(fileIdValue), Tools.toByte(etComSet1.getText().toString()), Offset, Length, pBuff);
                reader.DES_CommitTransaction();
                break;
            }
            case R.id.tv_back: {
                finish();
                break;
            }
        }
    }

    private String fileIdValue = "";

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

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

    }

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