package com.module.pay.serialport

import android.util.Log
import android_serialport_api.SerialPort
import com.elvishew.xlog.LogUtils
import com.module.pay.strategy.SerialPortStrategy
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream


class SerialPortUtil constructor(var handler: SerialPortStrategy) {
    private val TAG: String = "SerialPortUtil"
    private var serialPort: SerialPort? = null
    private var inputStream: InputStream? = null
    private var outputStream: OutputStream? = null
    private var isStart = false


    /**
     * 打开串口，接收数据
     * 通过串口，接收单片机发送来的数据
     */
    fun openSerialPort(path: String?, baudrate: Int, flags: Int, parity: Int) {
        try {
            serialPort = SerialPort(File(path), baudrate, flags, parity, 8, 1) //威佛
            //调用对象SerialPort方法，获取串口中"读和写"的数据流
            inputStream = serialPort?.getInputStream()
            outputStream = serialPort?.getOutputStream()
            isStart = true
        } catch (e: IOException) {
            e.printStackTrace()
        }

        getSerialPort()
    }


    /**
     * 关闭串口
     * 关闭串口中的输入输出流
     */
    fun closeSerialPort() {
        Log.i("test", "关闭串口")
        try {
            if (inputStream != null) {
                inputStream!!.close()
            }
            if (outputStream != null) {
                outputStream!!.close()
            }
            isStart = false
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    var lastData: String = ""

    /**
     * 发送数据
     * 通过串口，发送数据到单片机
     *
     * @param data 要发送的数据
     */
    fun sendSerialPort(data: String) {
        lastData = data
        XLogUtil.d("安卓发数据:$data")

        handler.sendData(data, outputStream)//每个策略发的不一样，所以需要他们自己发。 有的可能发十六进制，有的可能发ascii
//        try {
//            if (outputStream != null) {
//                val sendData: ByteArray = DataUtils.HexToByteArr(data)
//                outputStream!!.write(sendData)
//                outputStream!!.flush()
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
    }

    private fun getSerialPort() {
        try {
            mReceiveThread.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private val mReceiveThread = object : Thread() {
        override fun run() {
            super.run()
            //条件判断，只要条件为true，则一直执行这个线程
            val sber = StringBuilder()

            while (isStart) {
                if (inputStream == null) {
                    return
                }
                val readData = ByteArray(1024)
                try {
                    var size = 0

                    /** 获取流中数据的量 */
                    val i: Int = inputStream!!.available()
                    if (i == 0) {
                        size = 0
                    } else {
                        /** 流中有数据，则添加到临时数组中 */
                        size = inputStream!!.read(readData)
                    }
                    if (size > 0) {
                        handler.readData(readData, 0, size)
                        val readString: String =
                            DataUtils.ByteArrToHex(readData, 0, size)
                        XLogUtil.d(readString)
                        /*  EventBus.getDefault()
                              .post(WmdbIctMessageEvent(Name.ICT, readString))*/
                    }
                    sleep(30)
                } catch (e: Exception) {
                    e.printStackTrace()
                    sber.delete(0, sber.length)
                }
            }
        }
    }

    /**
     * 接收串口数据的线程
     */
    private class ReceiveThread : Thread() {
        override fun run() {
            super.run()

        }
    }
}