package h.com.newserialapp.activity.MIFAREClassicActivity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
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.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.Tools;
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.ICMessage;
import h.com.serialportapi.comn.message.IMessage;

/**
 * Created by hxd on 2018/11/30.
 */

public class MifareClassicActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    private FontTextView tvTagType, tvSAK, tvUIDNumber, tvDataRead, tvBack, tvStatus;
    private EditText etKey, etAPDUChannel, etWritingData;
    private Spinner spinnerADD, spinnerKeyType;
    private Button btActivieCard, btAuthenticate, btAPDUChannel, btReadBlock, btWriteBlock;
    private String[] addrArray;
    private String[] keyTypeArray;

    private Reader reader;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    tvTagType.setText(mICMessage.getTag_Type());
                    tvSAK.setText(mICMessage.getSAK());
                    tvUIDNumber.setText(mICMessage.getUID_number());
                    break;
                case 102:
                    if (!receiveCommand.substring(0, 2).equals("F0")) {
                        tvDataRead.setText(receiveCommand.substring(8, receiveCommand.length() - 2));
                    } else {
                        tvDataRead.setText("");
                    }
                    break;
            }
            return false;
        }
    });


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mifare_classic);
        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");
        tvTagType = findViewById(R.id.tv_tag_type);
        tvSAK = findViewById(R.id.tv_sak);
        tvUIDNumber = findViewById(R.id.tv_uid_number);
        tvBack = findViewById(R.id.tv_back);
        tvDataRead = findViewById(R.id.tv_data_read);
        tvStatus = findViewById(R.id.tv_status_bar);
        etKey = findViewById(R.id.et_key);
        etAPDUChannel = findViewById(R.id.et_apdu_channel);
        etWritingData = findViewById(R.id.et_write_data);
        spinnerADD = findViewById(R.id.spinner_addr);
        spinnerKeyType = findViewById(R.id.spinner_key_type);
        btActivieCard = findViewById(R.id.bt_active_card);
        btAuthenticate = findViewById(R.id.bt_authenticate);
        btAPDUChannel = findViewById(R.id.bt_apdu_channel);
        btReadBlock = findViewById(R.id.bt_read_block);
        btWriteBlock = findViewById(R.id.bt_write_block);
        btActivieCard.setOnClickListener(this);
        btAuthenticate.setOnClickListener(this);
        btAPDUChannel.setOnClickListener(this);
        btActivieCard.setOnClickListener(this);
        btReadBlock.setOnClickListener(this);
        btWriteBlock.setOnClickListener(this);
        tvBack.setOnClickListener(this);
        btActivieCard.setTypeface(typeface);
        btAuthenticate.setTypeface(typeface);
        btAPDUChannel.setTypeface(typeface);
        btActivieCard.setTypeface(typeface);
        btReadBlock.setTypeface(typeface);
        btWriteBlock.setTypeface(typeface);
        addrArray = getResources().getStringArray(R.array.block_addr);
        spinnerADD.setAdapter(new ArrayAdapter<>(this, R.layout.spinner_default_item, addrArray));
        keyTypeArray = getResources().getStringArray(R.array.key);
        spinnerKeyType.setAdapter(new ArrayAdapter<>(this, R.layout.spinner_default_item, keyTypeArray));
        spinnerADD.setOnItemSelectedListener(this);
        spinnerKeyType.setOnItemSelectedListener(this);
    }

    private byte[] all = new byte[]{10, 52};
    private byte[] idle = new byte[]{10, 26};
    private ICMessage mICMessage;
    private String receiveCommand;// serial port receive command

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_active_card: {
                byte[] pATQ = new byte[2];
                byte[] pSak = new byte[1];
                byte[] pUIDLen = new byte[1];
                byte[] pUID = new byte[16];

                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                int result = reader.PiccActivate((byte) 0x10, (byte) 0x26, pATQ, pSak, pUIDLen, pUID);
                if (result == 0) {
                    tvTagType.setText(Tools.toHexString(pATQ, pATQ.length));
                    tvSAK.setText(Tools.toHexString(pSak, 1));
                    tvUIDNumber.setText(Tools.toHexString(pUID, pUIDLen[0]));
                } else {
                    tvTagType.setText("-");
                    tvSAK.setText("-");
                    tvUIDNumber.setText("");
                }
                break;
            }
            case R.id.bt_authenticate: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                byte[] pSnr = Tools.toByteArray(tvUIDNumber.getText().toString());
                byte[] pKey = Tools.toByteArray(etKey.getText().toString());
                if (pSnr == null || pSnr.length != 4 || pKey == null || pKey.length != 6) {
                    Tools.showToast(this, "UID Number must be 4 bytes, and Key must be 6 bytes");
                    return;
                }
                byte auth_mode = (byte)(keyTypeValue.equals("KEYA") ? 0x60 : 0x61);
                reader.Picc_AuthKey(auth_mode, Tools.toByte(addrValue), pSnr, pKey);
                break;
            }
            case R.id.bt_apdu_channel: {
                int [] pRcvLen = new int[1];
                byte[] pRcvBuf = new byte[1024];

                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                byte[] pSendBuf = Tools.toByteArray(etAPDUChannel.getText().toString());
                if (pSendBuf == null || pSendBuf.length == 0) {
                    Tools.showToast(this, "APDU Channel is not null");
                    return;
                }
                reader.PiccTransfer(pSendBuf.length, pSendBuf, pRcvLen, pRcvBuf);
                break;
            }
            case R.id.bt_read_block: {
                byte[] pBuff = new byte[16];

                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                int result = reader.Picc_Read(Tools.toByte(addrValue), pBuff);
                if (result == 0) {
                    tvDataRead.setText(Tools.toHexString(pBuff, pBuff.length));
                } else {
                    tvDataRead.setText("");
                }
                break;
            }
            case R.id.bt_write_block: {
                tvStatus.setText("");
                if (reader == null) {
                    Tools.showToast(this, "Please open the serial port first.");
                    return;
                }
                byte[] pBuff = Tools.toByteArray(etWritingData.getText().toString());
                if (pBuff == null || pBuff.length != 16) {
                    Tools.showToast(this, "Writing Data must be 16 bytes");
                    return;
                }
                reader.Picc_Write(Tools.toByte(addrValue), pBuff);
                break;
            }
            case R.id.tv_back: {
                finish();
                break;
            }
        }
    }

    private String addrValue;
    private String keyTypeValue;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.spinner_addr:
                addrValue = addrArray[position];
                break;
            case R.id.spinner_key_type:
                keyTypeValue = keyTypeArray[position];
                break;
        }
    }

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

    }

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