package com.test.hfsimple;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.crccalc.Crc16;
import com.crccalc.CrcCalculator;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import cn.pda.serialport.SerialPort;
import cn.pda.serialport.Tools;

/**
 * Created by admin on 2017/4/6.
 */
public class TestActivity extends Activity implements View.OnClickListener{

    private Button btnOpen;
    private Button btnClear;
    private Button btnGetStatus;
    private Button btnGetIso14443A;
    private Button btnGetIso14443b;
    private Button btnGetLRFStandard;
    private Button btnGetIso15693;
    private Button btnGetInsdeSecure;
    private Button btnGetTag15693;
    private Button btnGetChipID;



    private TextView tvText;
    private int isOpen =0;
    private SerialPort mSerialport ;
    private InputStream inputStream;
    private OutputStream outputStream;

    private String getStruts ="0400005A52";


    private String getUid_RFstandard = "040100438A";
    private String getUid_15693 = "0401015203";
    private String getUid_14443A = "0401026098";
    private String getUid_14443B = "0401037111";
    private String getUid_Inside = "040104005A";
    private String getUid_SFsubset = "0401051427";

    private String getUidAndTag_RFstandard = "04170082CB";
    private String getUidAndTag_15693 = "0417019342";
    private String getUidAndTag_14443A = "041702A1D9";
    private String getUidAndTag_14443B = "041703B050";
    private String getUidAndTag_Inside = "041704C4EF";
    private String getUidAndTag_SFsubset = "041705D566" ;

    private String getChipId = "03F31FC4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        initView() ;
    }

    private void initView(){

        btnOpen = (Button) findViewById(R.id.btn_open);
        btnGetStatus = (Button)findViewById(R.id.btn_get_status);
        btnGetIso14443A = (Button) findViewById(R.id.btn_get_iso14443a);
        btnGetIso14443b = (Button) findViewById(R.id.btn_get_iso14443b);
        btnGetIso15693 = (Button) findViewById(R.id.btn_get_iso15693);
        btnGetLRFStandard = (Button) findViewById(R.id.btn_get_legicrfstandard);
        btnGetInsdeSecure = (Button) findViewById(R.id.btn_get_inside_secure);
        btnClear = (Button) findViewById(R.id.btn_clear);
        btnGetTag15693= (Button) findViewById(R.id.btn_get_iso15693_uid_tag);
        btnGetChipID= (Button) findViewById(R.id.btn_get_chip_id);

        btnOpen.setOnClickListener(this);
        btnGetStatus.setOnClickListener(this);
        btnGetIso14443A.setOnClickListener(this);
        btnGetIso14443b.setOnClickListener(this);
        btnGetIso15693.setOnClickListener(this);
        btnGetInsdeSecure.setOnClickListener(this);
        btnGetLRFStandard.setOnClickListener(this);
        btnClear.setOnClickListener(this);
        btnGetTag15693.setOnClickListener(this);
        btnGetChipID.setOnClickListener(this);

        tvText = (EditText)findViewById(R.id.ed_recv);
        tvText.setFocusable(false);
    }

    public boolean ClosePort(){
        if(mSerialport!=null){

            mSerialport.psampoweroff();
            mSerialport.close(14);
            return true;
        }else{
            return false;
        }
    }

    public boolean OpenPort(){
        try {
            mSerialport =  new SerialPort(14,38400,0);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        inputStream = mSerialport.getInputStream();
        outputStream = mSerialport.getOutputStream();
        mSerialport.psampoweron();
        return true;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_open:
                if(isOpen==0){

                    OpenPort();
                    btnOpen.setText("Close");
                    isOpen=1;
                    Toast.makeText(this,"Open com port success!",Toast.LENGTH_SHORT).show();
                }else if(isOpen==1){
                    ClosePort();
                    btnOpen.setText("Open");
                    isOpen=0;
                    Toast.makeText(this,"Close com port success!",Toast.LENGTH_SHORT).show();
                }/*
                String s ="041702";
                byte[] b1 = Check(com.test.hfsimple.Tools.HexString2Bytes(s));
                String r =  com.test.hfsimple.Tools.Bytes2HexString(b1,b1.length);
                Toast.makeText(this,r,Toast.LENGTH_SHORT).show();
                Log.d("hai-r",r);*/
                break;
            case R.id.btn_get_status:
                String RecvStatus = sendcmd(getStruts);
                if(RecvStatus !=null) {
                    Log.d("hai-", RecvStatus);
                    byte[] s1 = Check(com.test.hfsimple.Tools.HexString2Bytes(RecvStatus.substring(0,RecvStatus.length()-4)));
                    byte[] s2 = com.test.hfsimple.Tools.HexString2Bytes(RecvStatus.substring(RecvStatus.length()-4,RecvStatus.length()));
                    if((com.test.hfsimple.Tools.Bytes2HexString(s1, s1.length)).equals((com.test.hfsimple.Tools.Bytes2HexString(s2, s2.length)))){
                        Log.d("hai-s1", RecvStatus.substring(0, RecvStatus.length() - 4));
                        Log.d("hai-s1",com.test.hfsimple.Tools.Bytes2HexString(s1, s1.length));
                        Log.d("hai-s2",com.test.hfsimple.Tools.Bytes2HexString(s2, s2.length));
                        tvText.append("RecvStatus:"+RecvStatus + "\n");
                        if(RecvStatus.substring(6,RecvStatus.length()-4).equals("01")){
                            tvText.append("Application State is idle" + "\n");
                        }else if(RecvStatus.substring(6,RecvStatus.length()-4).equals("02")){
                            tvText.append("Application State is on" + "\n");
                        }
                    }else{
                        Toast.makeText(this, "Check the error", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(this,"Please open the serial port and power supply first.",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_get_iso14443a :
                String Recv14443a = sendcmd(getUid_14443A);
                if(Recv14443a!=null){
                    Log.d("hai-1",Recv14443a);
                    Toast.makeText(this,Recv14443a,Toast.LENGTH_SHORT).show();
                    tvText.append("Recv14443a:"+Recv14443a+"\n");
                    tvText.append("UID:"+GetUID(Recv14443a)+"\n");

                }else{
                    Toast.makeText(this,"Please open the serial port and power supply first.",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_get_iso14443b :
                String Recv14443b = sendcmd(getUid_14443B);

                if(Recv14443b!=null) {
                    Log.d("hai-1", Recv14443b);
                    Toast.makeText(this, Recv14443b, Toast.LENGTH_SHORT).show();
                    tvText.append("Recv14443b:" + Recv14443b + "\n");
                    tvText.append("UID:"+GetUID(Recv14443b)+"\n");
                }else {
                    Toast.makeText(this,"Please open the serial port and power supply first.",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_get_iso15693:
                String Recv15693 = sendcmd(getUid_15693);
                if(Recv15693!=null) {
                    Log.d("hai-1", Recv15693);
                    Toast.makeText(this, Recv15693, Toast.LENGTH_SHORT).show();
                    tvText.append("Recv15693:"+Recv15693 + "\n");
                    tvText.append("UID:"+GetUID(Recv15693)+"\n");
                }else {
                    Toast.makeText(this,"Please open the serial port and power supply first.",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_get_inside_secure :
                String RecvIS = sendcmd(getUid_Inside);
                if(RecvIS !=null) {
                    Log.d("hai-1", RecvIS);
                    Toast.makeText(this, RecvIS, Toast.LENGTH_SHORT).show();
                    tvText.append("Inside_secure:"+RecvIS + "\n");
                    tvText.append("UID:"+GetUID(RecvIS)+"\n");
                }else{
                    Toast.makeText(this,"Please open the serial port and power supply first.",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_get_legicrfstandard :
                String RecvRF= sendcmd(getUid_RFstandard);
                if(RecvRF != null) {
                    Log.d("hai-1", RecvRF);
                    Toast.makeText(this, RecvRF, Toast.LENGTH_SHORT).show();
                    tvText.append("LEGIC RF standard:"+RecvRF + "\n");
                    tvText.append("UID:"+GetUID(RecvRF)+"\n");
                }else{
                    Toast.makeText(this,"Please open the serial port and power supply first.",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_get_iso15693_uid_tag:
                String Recv= sendcmd(getUidAndTag_15693);
                if(Recv != null) {
                    Log.d("hai-1", Recv);
                    tvText.append("LEGIC RF standard:"+Recv + "\n");
                    byte[] a = Check(com.test.hfsimple.Tools.HexString2Bytes("101700000A0108E005100001188A62"));
                    Log.d("hai-",com.test.hfsimple.Tools.Bytes2HexString(a,a.length));
                }else{
                    Toast.makeText(this,"Please open the serial port and power supply first.",Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn_get_chip_id:
                String RecvGetChip = sendcmd(getChipId);
                tvText.append(RecvGetChip);
                byte[] byte1 = Check(com.test.hfsimple.Tools.HexString2Bytes(RecvGetChip.substring(0,RecvGetChip.length()-4)));
                byte[] byte2 = com.test.hfsimple.Tools.HexString2Bytes(RecvGetChip.substring(RecvGetChip.length()-4,RecvGetChip.length()));
                if((com.test.hfsimple.Tools.Bytes2HexString(byte1, byte1.length)).equals((com.test.hfsimple.Tools.Bytes2HexString(byte2, byte2.length)))){
                    Log.d("chipID",RecvGetChip.substring(4,6));
                    if(RecvGetChip.substring(4,6).equals("00")&&(RecvGetChip.length()>10)){
                        tvText.append(" Status, 00 = OK" +"\n");
                        tvText.append(" ChipID:"+RecvGetChip.substring(4,RecvGetChip.length()-4) +"\n");

                    }else if(RecvGetChip.substring(4,6).equals("01")){

                        tvText.append(" Status, 01 = general error"+"\n");
                        tvText.append(" ChipID:"+RecvGetChip.substring(4,RecvGetChip.length()-4) +"\n");

                    }else if(RecvGetChip.substring(4,6).equals("02")){
                        tvText.append(" Status,  02 = wrong command leng" +"\n");
                        tvText.append(" ChipID:"+RecvGetChip.substring(4,RecvGetChip.length()-4) +"\n");
                    }
                }
                break;
            case R.id.btn_clear:
                tvText.setText("");
                break;
        }
    }


    private byte[]  Check(byte[] bs)    {
        CrcCalculator calculator = new CrcCalculator(Crc16.Params[12]);
        long result = calculator.Calc(bs, 0, bs.length);
        byte[] bytes = Tools.HexString2Bytes(Long.toHexString(result).toUpperCase());
        return bytes;
    }

    public String GetUID(String Recv){
        if (Recv.length()>4){
        byte[] byte1 = Check(com.test.hfsimple.Tools.HexString2Bytes(Recv.substring(0,Recv.length()-4)));
        byte[] byte2 = com.test.hfsimple.Tools.HexString2Bytes(Recv.substring(Recv.length()-4,Recv.length()));
        if((com.test.hfsimple.Tools.Bytes2HexString(byte1, byte1.length)).equals((com.test.hfsimple.Tools.Bytes2HexString(byte2, byte2.length)))){
            if(Recv.length()>12) {
                return Recv.substring(10, Recv.length() - 4);
            }
            return "Not find cardUID";
        }
        }else {
            return "Not find cardUID";
        }
        return null;
    }

    private String sendcmd(String cmd) {
        if (outputStream != null) {
            try {
                inputStream.read(new byte[4960]);
                byte[] bytes = Tools.HexString2Bytes(cmd);
                outputStream.write(bytes);
                Thread.sleep(10);
                byte[] rbuf = new byte[128];
                byte[] recv = new byte[128];
                int lenTmp = 0;
                if (inputStream.available() >= 0&&lenTmp>=0) {
                    Thread.sleep(50);
                    lenTmp = inputStream.read(rbuf);
                    recv = new byte[lenTmp];
                    System.arraycopy(rbuf, 0, recv, 0, lenTmp);
                    return Tools.Bytes2HexString(recv, lenTmp);
                }
                // return receiveData(false);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
        return null;
    }

}