package com.bpa.scalage;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.bpa.scalage.helper.APIHelper;
import com.bpa.scalage.helper.Utils;
import com.bpa.scalage.mode.QRCodeModel;
import com.pc_rfid.api.PC_API;
import com.pc_rfid.api.RFdata;
import com.wsm.hidlib.HIDManager;
import com.wsm.hidlib.callback.HIDDataListener;
import com.wsm.hidlib.callback.HIDOpenListener;
import com.wsm.hidlib.callback.HIDSequenceNumberListener;
import com.wsm.hidlib.constant.FormatConstant;
import com.wsm.hidlib.util.StringFormat;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class PlateActivity extends AppCompatActivity {

    private Button btnWrite,btnScan,btnTest;
    private CheckBox cbOpen;
    private TextView txtStatus,txtCardUid,txtCardContent,txtCatdEwm,text_error;
    private EditText etData;

    private HIDSequenceNumberListener mHidSequenceNumberListener;

    private PC_API pcApi=new PC_API();
    private RFdata rFdata=new RFdata();
    private  boolean isConnected;

    /**
     * 绑定标签
     */
    private void BindingFlag(){
        try{
            text_error.setText("");
//        txtCardUid.setText("1122");
//        txtCatdEwm.setText("http://www.baidu.com");
            if(txtCardContent.getText().toString().isEmpty()){
                text_error.setText("RFID 标签不能为空");
                return;
            }
            if(txtCatdEwm.getText().toString().isEmpty()){
                text_error.setText("二维码内容不能为空");
                return;
            }
            //https://bpa.black-pa.com:21995/
            //111.9.47.105
            String catdEwm=txtCatdEwm.getText().toString().replace("\n","");
            QRCodeModel qm = new QRCodeModel(catdEwm,txtCardContent.getText().toString(),catdEwm.contains("isPay=true"));
            APIHelper.Post("https://www.black-pa.com:21996/groupmeal/api/ExternalPlatform/DiningPlate/EditDiningPlateByQRCode",qm,s->{
                try{
                    if(s.errors!=null&& !s.errors.isEmpty()) this.runOnUiThread(()->{text_error.setText(s.errors);});
                    if(s.statusCode==200) this.runOnUiThread(()->{text_error.setText("芯片绑定成功");});
                }catch(Exception e){
                    this.runOnUiThread(()->{text_error.setText("芯片绑定失败");});
                }
            },(error)->{
                this.runOnUiThread(()->{text_error.setText(error);});
            });
        }catch (Exception e){

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        Thread.setDefaultUncaughtExceptionHandler(new );

        setContentView(R.layout.activity_plate);
        cbOpen=findViewById(R.id.cb_open);
        btnWrite=findViewById(R.id.btn_write);
        btnScan=findViewById(R.id.btn_scan);
        btnTest=findViewById(R.id.btn_test);
        txtStatus=findViewById(R.id.txt_status);
        txtCardUid=findViewById(R.id.txt_cardUid);
        txtCardContent=findViewById(R.id.txt_cardContent);
        txtCatdEwm=findViewById(R.id.txt_cardEwm);
        etData=findViewById(R.id.et_data);
        text_error=findViewById(R.id.text_error);

//        aa();
        Utils.disableSSLCertChecking();
        btnTest.setOnClickListener((view)->{
            BindingFlag();
        });

        txtStatus.setText("未就绪");
        btnWrite.setEnabled(false);
        cbOpen.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    if(isConnected)
                        return;
                    try{
                        boolean res = pcApi.PC_OpenCOM("/dev/ttyS4", 38400, "8N1");
                        if (res) {
                            txtStatus.setText("已就绪");
                            btnWrite.setEnabled(true);
                            readLoop();
                            isConnected=true;
                        }
                    }catch(Exception e) {

                    }
                }else{
                    boolean res = pcApi.PC_Close();
                    if (res) {
                        txtStatus.setText("未连接");
                        btnWrite.setEnabled(false);
                        txtCardUid.setText("");
                        txtCardContent.setText("");
                        etData.setText("");
                    }
                    isConnected=false;
                }
            }
        });


//        btnRead.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                boolean res= pcApi.PC_InventoryTag(rFdata,(byte) 0x04);
//                if(res){
//                    try {
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
//                    byte[] temp=Arrays.copyOfRange(rFdata.RecvData,7,15);
//                    rFdata.clear();
//                    res=pcApi.PC_ReadCardOneBlock(rFdata,temp,(byte) 1,(byte)0,(byte)0);
//                    temp=Arrays.copyOfRange(rFdata.RecvData,8,12);
//                    String content=new String(temp, StandardCharsets.US_ASCII);
//                    etData.setText(content);
//                }
//            }
//        });
        btnWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try{
                    int temp=Integer.parseInt(etData.getText().toString());
                    if(temp<0||temp>9999){
                        text_error.setText("请输入0-9999的整数");
                    }else{
                        etData.setText(String.format("%04d",temp));
                        etData.setSelection(etData.length());
                    }
                }catch(Exception e){
                    text_error.setText("请输入0-9999的整数");
                }
                writeBuffer.add(etData.getText().toString());
            }
        });

        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(PlateActivity.this);
                LayoutInflater inflater = LayoutInflater.from(PlateActivity.this);
                View v = inflater.inflate(R.layout.pop_scanner_view, null);
                EditText content = (EditText) v.findViewById(R.id.et_scan_content);
                Button btnScanOK = (Button) v.findViewById(R.id.btn_scan_ok);
                Button btn_cancel = (Button) v.findViewById(R.id.btn_scan_cancel);

                final Dialog dialog = builder.create();
                btnScanOK.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        txtCatdEwm.setText(content.getText().toString());
                        dialog.dismiss();
                    }
                });
                btn_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
                dialog.getWindow().setContentView(v);
                content.requestFocus();
                content.setFocusableInTouchMode(true);
            }
        });
//        mHidSequenceNumberListener = new HIDSequenceNumberListener() {
//            @Override
//            public void onSequenceNumberReceived(byte[] bytes, int length) {
//                if (length > 0) {
//                    String formatChar = StringFormat.bytes2String(bytes, FormatConstant.FORMAT_UTF8);
//                    Message message = Message.obtain();
//                    message.what = READ_OK;
//                    message.obj = formatChar;
//                    handler.sendMessage(message);
//                }
//            }
//        };
//        HIDManager.getInstance().getSequenceNumber(mHidSequenceNumberListener);
        HIDManager.getInstance().openHID(getApplicationContext(), new HIDOpenListener() {
            @Override
            public void openSuccess(int i) {

            }

            @Override
            public void openError(int i) {

            }
        }, new HIDDataListener() {
            @Override
            public void onDataReceived(byte b, String s) {

            }

            @Override
            public void onOriginalDataReceived(byte b, byte[] bytes, int i) {
                String formatChar = StringFormat.bytes2String(bytes, FormatConstant.FORMAT_UTF8);
            }
        });
    }

    Queue<String> writeBuffer=new PriorityQueue<>();

    private void extracted() {
        while (writeBuffer.size()>0) {
            try{
                boolean res = pcApi.PC_InventoryTag(rFdata, (byte) 0x04);
                if (res) {
                    Thread.sleep(500);
                    byte[] temp = Arrays.copyOfRange(rFdata.RecvData, 7, 15);
                    rFdata.clear();
                    byte[] content = writeBuffer.poll().getBytes(StandardCharsets.US_ASCII);
                    res = pcApi.PC_WriteCardOneBlock(rFdata, temp, (byte) 1, (byte) 0, content);
                }
            }catch(Exception e){

            }
        }
    }

    private void readLoop(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isConnected) {
                    extracted();
                    try{
                        boolean res = pcApi.PC_InventoryTag(rFdata, (byte) 0x04);
                        if (res) {
                            Thread.sleep(100);
                            byte[] temp = Arrays.copyOfRange(rFdata.RecvData, 7, 15);
                            String uid = readByte(temp);
                            if(!"10000000".equals(uid)) {
                                rFdata.clear();
                                pcApi.PC_ReadCardOneBlock(rFdata, temp, (byte) 1, (byte) 0, (byte) 0);
                                temp = Arrays.copyOfRange(rFdata.RecvData, 8, 12);
                                String content = new String(temp, StandardCharsets.US_ASCII);
                                runOnUiThread(()->{
                                    txtCardUid.setText(uid);
                                    txtCardContent.setText(content);
                                });
                            }else{
                                runOnUiThread(()->{
                                    txtCardUid.setText("");
                                    txtCardContent.setText("");
                                });
                            }
                        }
                        Thread.sleep(100);
                    }catch(Exception e){

                    }
                }
            }
        }).start();
    }

    private String readByte(byte[] b) {
        StringBuilder sb  = new StringBuilder();
        for(int i=0;i<b.length;i++){
            if(i==0){
                sb.append(Integer.toHexString(b[i]&0xff));
            }else if(i>0){
                sb.append(Integer.toHexString(b[i]&0xff));
            }
        }
        String ser = sb.toString();
        return ser;
    }
}