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.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 PiccLevelActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    private FontTextView tvApplicationIds, tvBack, tvStatus;
    private FontEditText etApplicationID02, etKeySetting, etKeyNumber;
    private Button btGetAPP, btSelectAPP, btDeleteAPP, btCreateAPP, btFormatPICC;
    private Spinner spinnerApplicationID;

    private int forvalue;
    private String[] appIDS;
    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")){
                        forvalue = Integer.valueOf(tempCommand.substring(8, 10));
                        if (forvalue != 0) {
                            tvApplicationIds.setText("");
                            appIDS = new String[forvalue];
                            for (int i = 0; i < forvalue; i++) {
                                appIDS[i] = tempCommand.substring(10 + i * 6, 16 + i * 6);
                            }
                            for (int j = 0; j < forvalue; j++) {
                                tvApplicationIds.append(appIDS[j] + "\n");
                            }
                            spinnerApplicationID.setAdapter(new ArrayAdapter<String>(PiccLevelActivity.this, R.layout.spinner_default_item, appIDS));
                        }
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picc_level);
        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");
        tvApplicationIds = findViewById(R.id.tv_application_ids);
        tvBack = findViewById(R.id.tv_back);
        tvStatus = findViewById(R.id.tv_status_bar);
        spinnerApplicationID = findViewById(R.id.et_application_id);
        etApplicationID02 = findViewById(R.id.et_application_id_2);
        etKeySetting = findViewById(R.id.et_key_setting);
        etKeyNumber = findViewById(R.id.et_key_number);
        btGetAPP = findViewById(R.id.bt_get_app);
        btSelectAPP = findViewById(R.id.bt_select_app);
        btDeleteAPP = findViewById(R.id.bt_delete_app);
        btCreateAPP = findViewById(R.id.bt_create_app);
        btFormatPICC = findViewById(R.id.bt_format_picc);
        tvBack.setOnClickListener(this);
        btGetAPP.setOnClickListener(this);
        btSelectAPP.setOnClickListener(this);
        btDeleteAPP.setOnClickListener(this);
        btCreateAPP.setOnClickListener(this);
        btFormatPICC.setOnClickListener(this);
        btGetAPP.setTypeface(typeface);
        btSelectAPP.setTypeface(typeface);
        btDeleteAPP.setTypeface(typeface);
        btCreateAPP.setTypeface(typeface);
        btFormatPICC.setTypeface(typeface);
        appIDS = getResources().getStringArray(R.array.nulls);
        spinnerApplicationID.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner_default_item, appIDS));
        spinnerApplicationID.setOnItemSelectedListener(this);
    }

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

                tvStatus.setText("");
                tvApplicationIds.setText("");
                appIDS = getResources().getStringArray(R.array.nulls);
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                int result = reader.GetApplicationIDs(pAIDs, pAIDno);
                if (result == 0 && pAIDno[0] != 0) {
                    appIDS = new String[pAIDno[0]];
                    for (int i = 0; i < pAIDno[0]; i += 3) {
                        appIDS[i] = String.format("%02X %02X %02X", pAIDs[i], pAIDs[i + 1], pAIDs[i + 2]);
                        tvApplicationIds.append(appIDS[i] + "\n");
                    }
                }
                spinnerApplicationID.setAdapter(new ArrayAdapter<>(PiccLevelActivity.this, R.layout.spinner_default_item, appIDS));
                break;
            }
            case R.id.bt_select_app: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(tempAppIDs)) {
                    Tools.showToast(this, "Application ID parameter is null");
                    return;
                }
                byte[] AppID = Tools.toByteArray(tempAppIDs);
                if (AppID == null || AppID.length != 3) {
                    Tools.showToast(this, "Application ID parameter is null");
                    return;
                }
                reader.DESSelectApplication(AppID);
                break;
            }
            case R.id.bt_delete_app: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                if (Tools.isNull(tempAppIDs)) {
                    Tools.showToast(this, "Application ID parameter is null");
                    return;
                }
                byte[] AppID = Tools.toByteArray(tempAppIDs);
                if (AppID == null || AppID.length != 3) {
                    Tools.showToast(this, "Application ID parameter is null");
                    return;
                }
                reader.DESDeleteApplication(AppID);
                break;
            }
            case R.id.bt_create_app: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                byte[] AppID = Tools.toByteArray(etApplicationID02.getText().toString());
                if (AppID == null || AppID.length != 3 || Tools.isNull(etKeySetting.getText().toString()) || Tools.isNull(etKeyNumber.getText().toString())) {
                    Tools.showToast(this, "Create APP parameter Application and Key Setting, Key Number is not null");
                    return;
                }
                reader.DESCreateApplication(AppID, Tools.toByte(etKeySetting.getText().toString()), Tools.toByte(etKeyNumber.getText().toString()));
                break;
            }
            case R.id.bt_format_picc: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                reader.DESFormatPicc();
                break;
            }
            case R.id.tv_back: {
                finish();
                break;
            }
        }
    }

    private String tempAppIDs = "";

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

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

    }

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

}
