package h.com.newserialapp.activity.AutoOperationActivity;

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.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

import h.com.newserialapp.R;
import h.com.newserialapp.views.FontTextView;
import h.com.serialportapi.comn.Reader;
import h.com.serialportapi.comn.SerialPortManager;

/**
 * Created by hxd on 2019/5/21.
 */

public class AutoActivity extends AppCompatActivity implements View.OnClickListener {

    private CheckBox cbISO14443A, cbISO14443B, cbISO15693, cbAllTypes;
    private Button btStart, btStop, btClear;
    private FontTextView tvRecord;

    private Reader  reader;
    private boolean isRunning;
    private String  message = "";

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                refreshLogView(message);
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto);

        reader = SerialPortManager.instance().reader;
        if (reader == null) {
            Toast.makeText(this, "Please open the serial port first.", Toast.LENGTH_LONG).show();
            return;
        } else {
            reader.setLisenter(false);
        }
        initData();
    }

    @Override
    protected void onDestroy() {
        isRunning = false;
        super.onDestroy();
    }

    void initData() {
        cbISO14443A = findViewById(R.id.cbISO14443A);
        cbISO14443B = findViewById(R.id.cbISO14443B);
        cbISO15693 = findViewById(R.id.cbISO15693);
        cbAllTypes = findViewById(R.id.cbAllTypes);
        btStart = findViewById(R.id.start_bt);
        btStop = findViewById(R.id.stop_bt);
        btClear = findViewById(R.id.clear_bt);
        tvRecord = findViewById(R.id.tvRecord);
        tvRecord.setMovementMethod(ScrollingMovementMethod.getInstance());

        btStart.setOnClickListener(this);
        btStop.setOnClickListener(this);
        btClear.setOnClickListener(this);

        cbISO14443A.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (cbISO14443A.isChecked()) {
                    cbAllTypes.setChecked(false);
                }
            }
        });
        cbISO14443B.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (cbISO14443B.isChecked()) {
                    cbAllTypes.setChecked(false);
                }
            }
        });
        cbISO15693.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (cbISO15693.isChecked()) {
                    cbAllTypes.setChecked(false);
                }
            }
        });
        cbAllTypes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (cbAllTypes.isChecked()) {
                    cbISO14443A.setChecked(false);
                    cbISO14443B.setChecked(false);
                    cbISO15693.setChecked(false);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_bt:
                isRunning = true;
                new ReadThread().start();
                break;
            case R.id.stop_bt:
                isRunning = false;
                break;
            case R.id.clear_bt:
                tvRecord.setText("");
                break;
        }
    }

    private class ReadThread extends Thread {

        @Override
        public void run() {
            int result;
            byte[] pATQ = new byte[2];
            byte[] pSak = new byte[1];
            byte[] pUIDLen = new byte[1];
            byte[] pUID = new byte[32];

            while (isRunning) {
                if (isRunning && cbAllTypes.isChecked()) {
                    if (isRunning) {
                        result = SerialPortManager.instance().reader.PiccActivate((byte)0x10, (byte)0x26, pATQ, pSak, pUIDLen, pUID);
                        if (result == 0) {
                            String str = "";
                            message = "one card be detected:\nISO14443A standard\n";
                            for (int i = 0; i < pUIDLen[0]; i++) {
                                str += String.format("%02X", pUID[i]);
                            }
                            message += "UID:" + str + "    CardType:" + String.format("%02X%02X", pATQ[0], pATQ[1]) + "    SAK:" + String.format("%02X", pSak[0]) + "\n";
                            message += getCurrentDateTime() + "\n\n";
                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if (isRunning) {
                        result = SerialPortManager.instance().reader.PiccActivateB((byte)0x00, (byte)0x00, (byte)0x00, pUIDLen, pUID);
                        if (result == 0) {
                            String str = "";
                            message = "one card be detected:\nISO14443B standard\n";
                            for (int i = 0; i < pUIDLen[0]; i++) {
                                str += String.format("%02X", pUID[i]);
                            }
                            message += "Card message:" + str + "\n";
                            message += getCurrentDateTime() + "\n\n";
                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if (isRunning) {
                        result = SerialPortManager.instance().reader.ISO15693_Inventory((byte)0x26, (byte)0x00, (byte)0x00, null, pUIDLen, pUID);
                        if (result == 0) {
                            String str = "";
                            message = "one card be detected:\nISO15693 standard\n";
                            for (int i = 0; i < pUIDLen[0]; i++) {
                                str += String.format("%02X", pUID[i]);
                            }
                            message += "UID:" + str + "\n";
                            message += getCurrentDateTime() + "\n\n";
                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if (isRunning && cbISO14443A.isChecked()) {
                        result = SerialPortManager.instance().reader.PiccActivate((byte)0x10, (byte)0x26, pATQ, pSak, pUIDLen, pUID);
                        if (result == 0) {
                            String str = "";
                            message = "one card be detected:\nISO14443A standard\n";
                            for (int i = 0; i < pUIDLen[0]; i++) {
                                str += String.format("%02X", pUID[i]);
                            }
                            message += "UID:" + str + "    CardType:" + String.format("%02X%02X", pATQ[0], pATQ[1]) + "    SAK:" + String.format("%02X", pSak[0]) + "\n";
                            message += getCurrentDateTime() + "\n\n";
                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (isRunning && cbISO14443B.isChecked()) {
                        result = SerialPortManager.instance().reader.PiccActivateB((byte)0x00, (byte)0x00, (byte)0x00, pUIDLen, pUID);
                        if (result == 0) {
                            String str = "";
                            message = "one card be detected:\nISO14443B standard\n";
                            for (int i = 0; i < pUIDLen[0]; i++) {
                                str += String.format("%02X", pUID[i]);
                            }
                            message += "Card message:" + str + "\n";
                            message += getCurrentDateTime() + "\n\n";
                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (isRunning && cbISO15693.isChecked()) {
                        result = SerialPortManager.instance().reader.ISO15693_Inventory((byte)0x26, (byte)0x00, (byte)0x00, null, pUIDLen, pUID);
                        if (result == 0) {
                            String str = "";
                            message = "one card be detected:\nISO15693 standard\n";
                            for (int i = 0; i < pUIDLen[0]; i++) {
                                str += String.format("%02X", pUID[i]);
                            }
                            message += "UID:" + str + "\n";
                            message += getCurrentDateTime() + "\n\n";
                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    private String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sdf.format(new Date());
    }

    private void refreshLogView(String msg) {
        tvRecord.append(msg);
        int offset = tvRecord.getLineCount()*tvRecord.getLineHeight();
        if (offset > tvRecord.getHeight()) {
            tvRecord.scrollTo(0,offset-tvRecord.getHeight());
        }
    }

}

