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.SerialAPP;
import h.com.newserialapp.activity.BaseActivity;
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 FileInformation extends BaseActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    private FontTextView tvFileIDS, tvFileType, tvCommSet, tvAccessRight, tvFileSize, tvBack, tvStatus;
    private Spinner spinnerFileID, spinnerFileID02;
    private FontEditText etFileID, etCommSet, etAccessRight;
    private Button btGetFileID, btDeleteFile, btGetFileSetting, btChangeFileSetting;

    private int forvalue;
    private String[] fileIds;

    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")) {
                        forvalue = Integer.valueOf(tempCommand.substring(8, 10));
                        if (forvalue != 0) {
                            tvFileIDS.setText("");
                            fileIds = new String[forvalue];
                            for (int i = 0; i < forvalue; i++) {
                                fileIds[i] = tempCommand.substring(10 + i * 2, 12 + i * 2);
                            }
                            for (int j = 0; j < forvalue; j++) {
                                tvFileIDS.append(fileIds[j] + "\n");
                            }
                            spinnerFileID.setAdapter(new ArrayAdapter<String>(FileInformation.this, R.layout.spinner_default_item, fileIds));
                            spinnerFileID02.setAdapter(new ArrayAdapter<String>(FileInformation.this, R.layout.spinner_default_item, fileIds));
                            SerialAPP.setFileIds(fileIds);
                        }
                    }
                    break;
                case 102:
                    if (!tempCommand.substring(0, 2).equals("F0")) {
                        tvFileType.setText(tempCommand.substring(8, 12));
                        tvCommSet.setText(tempCommand.substring(12, 14));
                        tvAccessRight.setText(tempCommand.substring(14, 18));
                        tvFileSize.setText(tempCommand.substring(18, tempCommand.length() - 2));
                    }
                    break;
            }
            return false;
        }
    });


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_information);
        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");
        tvFileIDS = findViewById(R.id.tv_file_ids);
        tvFileType = findViewById(R.id.tv_file_type);
        tvCommSet = findViewById(R.id.tv_ComSet);
        tvAccessRight = findViewById(R.id.tv_acsess_right);
        tvFileSize = findViewById(R.id.tv_file_size);
        tvBack = findViewById(R.id.tv_back);
        tvStatus = findViewById(R.id.tv_status_bar);
        spinnerFileID = findViewById(R.id.spinner_file_id);
        spinnerFileID02 = findViewById(R.id.spinner_file_id_2);
        etFileID = findViewById(R.id.et_file_id);
        etCommSet = findViewById(R.id.et_ComSet);
        etAccessRight = findViewById(R.id.et_access_right);
        btGetFileID = findViewById(R.id.bt_get_file_id);
        btDeleteFile = findViewById(R.id.bt_delete_file);
        btGetFileSetting = findViewById(R.id.bt_get_file_setting);
        btChangeFileSetting = findViewById(R.id.bt_change_file_setting);
        tvBack.setOnClickListener(this);
        btGetFileID.setOnClickListener(this);
        btDeleteFile.setOnClickListener(this);
        btGetFileSetting.setOnClickListener(this);
        btChangeFileSetting.setOnClickListener(this);
        fileIds = getResources().getStringArray(R.array.nulls);
        spinnerFileID.setAdapter(new ArrayAdapter<>(this, R.layout.spinner_default_item, fileIds));
        spinnerFileID02.setAdapter(new ArrayAdapter<>(this, R.layout.spinner_default_item, fileIds));
        spinnerFileID.setOnItemSelectedListener(this);
        spinnerFileID02.setOnItemSelectedListener(this);
        btGetFileID.setTypeface(typeface);
        btDeleteFile.setTypeface(typeface);
        btGetFileSetting.setTypeface(typeface);
        btChangeFileSetting.setTypeface(typeface);
    }

    private String tempCommand;

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

                tvStatus.setText("");
                tvFileIDS.setText("");
                fileIds = getResources().getStringArray(R.array.nulls);
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                int result = reader.DESGetFileIDs(pIDs, pFileIDs);
                if (result == 0 && pIDs[0] != 0) {
                    fileIds = new String[pIDs[0]];
                    for (int i = 0; i < pIDs[0]; i++) {
                        fileIds[i] = String.format("%02X", pFileIDs[i]);
                        tvFileIDS.append(fileIds[i] + "\n");
                    }
                }
                spinnerFileID.setAdapter(new ArrayAdapter<>(FileInformation.this, R.layout.spinner_default_item, fileIds));
                spinnerFileID02.setAdapter(new ArrayAdapter<>(FileInformation.this, R.layout.spinner_default_item, fileIds));
                SerialAPP.setFileIds(fileIds);
                break;
            }
            case R.id.bt_delete_file: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(fileIDSValue)) {
                    Tools.showToast(this, "Fild Ids is null");
                    return;
                }
                reader.DESDeleteDESFile(Tools.toByte(fileIDSValue));
                break;
            }
            case R.id.bt_get_file_setting: {
                byte[] pInfoLen = new byte[1];
                byte[] pFileInfo = new byte[32];

                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(fileIDS02Value)) {
                    Tools.showToast(this, "Fild Ids is null");
                    return;
                }
                int result = reader.DESGetFileSettings(Tools.toByte(fileIDS02Value), pInfoLen, pFileInfo);
                if (result == 0) {
                    if (pFileInfo[0] == 0x07) {
                        tvFileType.setText(String.format("%02X", pFileInfo[1]));
                        tvCommSet.setText(String.format("%02X", pFileInfo[2]));
                        tvAccessRight.setText(String.format("%02X %02X", pFileInfo[3], pFileInfo[4]));
                        tvFileSize.setText(String.format("%02X %02X", pFileInfo[5], pFileInfo[6]));
                    } else {
                        tvFileType.setText(String.format("%02X", pFileInfo[0]));
                        tvCommSet.setText(String.format("%02X", pFileInfo[1]));
                        tvAccessRight.setText(String.format("%02X %02X", pFileInfo[2], pFileInfo[3]));
                        tvFileSize.setText(String.format("%02X %02X", pFileInfo[4], pFileInfo[5]));
                    }
                } else {
                    tvFileType.setText("");
                    tvCommSet.setText("");
                    tvAccessRight.setText("");
                    tvFileSize.setText("");
                }
                break;
            }
            case R.id.bt_change_file_setting: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(etFileID.getText().toString()) || Tools.isNull(etCommSet.getText().toString())) {
                    Tools.showToast(this, "File ID and ComSet is null");
                    return;
                }
                byte[] AccessRight = Tools.toByteArray(etAccessRight.getText().toString());
                if (AccessRight == null || AccessRight.length != 2) {
                    Tools.showToast(this, "Access Right must be 2 bytes");
                    return;
                }
                reader.DESChangeFileSettings(Tools.toByte(etFileID.getText().toString()), Tools.toByte(etCommSet.getText().toString()), AccessRight);
                break;
            }
            case R.id.tv_back: {
                finish();
                break;
            }
        }
    }

    private String fileIDSValue = "";
    private String fileIDS02Value = "";

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

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

    }

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

}
