package com.hh.arome.common.scan.broadcast.d2;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.telpo.tps550.api.qrcode.QrcodePower;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;

import android_serialport_api.SerialPort;


/**
 * Created by ljj on 2018/12/11
 * 读取485的数据
 */
public class SerialRecvThread implements SerialData{

    private static final String TAG = "HHArome";
    private InputStream mInputStream;
    private static SerialPort mSerialPort;
    private SerialDataListener mListener;
    private final int baudrate = 9600;//115200;
    private final int flags = 0;
    private ReadThread mReadThread;
    private String mData = "";
    QrcodePower qrcodePower;
    private class ReadThread extends Thread {

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void run() {
            super.run();
            while(!isInterrupted()) {
                int size;
                if(!canRunning){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                try {

                    byte[] buffer = new byte[1024];
                    if (mInputStream == null) {
                      initSerialPort();
                      continue;
                    }
//                    Log.e(TAG, "SerialQrReaderFactory1  mInputStream.available():"+mInputStream.available());
                    if(mInputStream.available() == 0 && !mData.isEmpty()){
                        Log.e(TAG, "SerialQrReaderFactory1_4 bufferStr:"+mData);
                        String bufferStr1 = mData;
                        mData = "";
                        if(mListener != null){
                            mListener.onReadSerialData(bufferStr1);
                        }
                    }

                    //if(mInputStream.available() > 0 ){
                    size = mInputStream.read(buffer);
                    if(size > 0) {
                        String bufferStr = new String(Arrays.copyOf(buffer, size), StandardCharsets.UTF_8);
//                        Log.e(TAG, "SerialQrReaderFactory1_1 bufferStr:"+bufferStr);
                        mData += bufferStr;
                    }
                    //}


                } catch (IOException e) {
                    initSerialPort();
                    e.printStackTrace();
                    mData = "";
                    //return;
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    Context context;
    private volatile boolean canRunning = false;

    public SerialRecvThread(){

    }

    public SerialRecvThread(Context context){
        this.context = context;
    }

//    String pathname = "/dev/ttyS0";//
//    String pathname = "/dev/ttyS1";//
//    String pathname = "/dev/ttyACM0";
//    String pathname = "/dev/ttyACM1";
    String pathname = "/dev/ttyHSL0";

    /**
     * 初始化串口
     */
    private void initSerialPort() {
        boolean iniOk = true;
        if(Build.MODEL.contains("TPS360")){
            if(!isBarcodeReaderConnected()) {
                if (qrcodePower == null) {
                    qrcodePower = new QrcodePower();
                }
                qrcodePower.open_em();
                return;
            }
        }


        try {
            if(mSerialPort != null){
                mSerialPort.close();
            }
//            String pathname = "/dev/ttyS1";//AppOptions.getInstance().getSerialDev();
//            String pathname = "/dev/ttyS0";//AppOptions.getInstance().getSerialDev();
//            String pathname = "/dev/ttyACM0";//AppOptions.getInstance().getSerialDev();
//            String pathname = "/dev/ttyACM1";//AppOptions.getInstance().getSerialDev();
            mSerialPort = new SerialPort(new File(pathname), baudrate, flags);
            mInputStream = mSerialPort.getInputStream();
            Log.e(TAG, "initSerialPort ttyACM0 ok baudrate: " + baudrate + " flags: " + flags);
        } catch (Exception e) {
            iniOk = false;
            if(mInputStream != null) {
                close(mInputStream);
            }
            if(mSerialPort != null){
                mSerialPort.close();
            }
            PowerClose360();
            //Log.e(TAG, e.getMessage());
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!iniOk){
            try {
                if(mSerialPort != null){
                    mSerialPort.close();
                }
//                String pathname = "/dev/ttyACM1";//AppOptions.getInstance().getSerialDev();
                mSerialPort = new SerialPort(new File(pathname), baudrate, flags);
                mInputStream = mSerialPort.getInputStream();
                Log.e(TAG, "initSerialPort ttyACM1 ok baudrate: " + baudrate + " flags: " + flags);
            } catch (Exception e) {
                if(mInputStream != null) {
                    close(mInputStream);
                }
                if(mSerialPort != null){
                    mSerialPort.close();
                }
                PowerClose360();
            }
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //360设备确认扫码设备是否正常
    private boolean isBarcodeReaderConnected() {
        UsbManager usbManager = (UsbManager) this.context.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> usbList = usbManager.getDeviceList();
        for (String key : usbList.keySet()) {
            UsbDevice usbDevice = usbList.get(key);
            if (usbDevice != null && usbDevice.getProductId() == 0x1d06 && usbDevice.getVendorId() == 0x1eab) {
                return true;
            }
        }
        return false;
    }

    /**
     * 停止线程
     */
    @Override
    public void stop() {
        Log.e(TAG, "stop");
        canRunning = false;
        if (mReadThread != null)
            mReadThread.interrupt();

        if(mInputStream != null) {
            close(mInputStream);
        }
        if(mSerialPort != null) {
            mSerialPort.close();
        }
        mSerialPort = null;
        mListener = null;
        PowerClose360();
    }

    private void PowerClose360() {
//        if(Build.MODEL.contains("TPS360")) {
//            if (qrcodePower == null) {
//                qrcodePower = new QrcodePower();
//            }
//            qrcodePower.close_em();
//        }
    }

    /**
    * 设置返回数据
    */
    @Override
    public void setListener(SerialDataListener listener) {
        mListener = listener;
    }

    /**
    * 关闭流
    */
    private void close(Closeable os){
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                Log.e(TAG,e.getMessage());
            }
        }
    }

    /**
     * 输入串口的数据
     * @param data
     */
    @Override
    public void send(String data) {

    }

    /**
     * 打开线程 默认参数
     */
    @Override
    public void start(){
        Log.e(TAG, "start");
        canRunning = true;
        initSerialPort();
        mReadThread = new ReadThread();
        mReadThread.start();
    }

}
