package com.develop.foodcooking

import android.serialport.SerialPort
import android.util.Log
import com.kuyuntech.cofarcooking.device.sdk.eventbus.event.Dev2McuDataEvent
import com.kuyuntech.cofarcooking.device.sdk.eventbus.listener.Dev2McuEventListener
import com.kuyuntech.cofarcooking.device.sdk.eventbus.listener.Mcu2DevEventListener
import com.kuyuntech.cofarcooking.device.sdk.protocol.core.BaseDecoder
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import com.kuyuntech.cofarcooking.device.sdk.util.core.Converter
import java.io.File
import java.io.IOException

object SerialManager {
    private var serialPortPath = "/dev/ttyS1"
    private var baudRate = 9600
    private var dataBits = 8
    private var parity = 0
    private var stopBits = 1
    private var flags = 0
    private var isOpen = false

    private var serialPort: SerialPort? = null
    private var readThread: ReadThread? = null

    fun openSerialPort() {
        if (!isOpen) {
            serialPort =
                SerialPort(File(serialPortPath), baudRate, dataBits, parity, stopBits, flags)
            val dev2McuEventListener = Dev2McuEventListener { event: Dev2McuDataEvent ->
                Log.i("dev2mcu:", event.data)
                val data =
                    Converter.hexStringToBytes(
                        event.data
                    )
                try {
                    serialPort?.outputStream?.write(data)
                } catch (e: IOException) {
                    e.printStackTrace()
                    closeSerialPort()
                }
            }
            CofarSDK.register(dev2McuEventListener)
            CofarSDK.register(Mcu2DevEventListener())
            readThread = ReadThread()
            readThread?.start()
            isOpen = true
        }
    }


    fun closeSerialPort() {
        isOpen = false
        serialPort?.close()
        readThread?.interrupt()
        readThread = null
        serialPort = null
    }

    class ReadThread : Thread() {
        private val bytes: MutableList<Byte> = ArrayList()

        override fun run() {
            try {
                var tmp = ByteArray(1024)
                var len = -1

                while (serialPort?.inputStream?.read(tmp).also {
                        if (it != null) {
                            len = it
                        }
                    } != -1) {
                    val cmdTmp = tmp.copyOf(len)
                    tmp = ByteArray(1024)
                    for (b in cmdTmp) {
                        if (b.toInt() == 0x7e) {
                            if (bytes.size == 0) {
                                bytes.add(b)
                            } else {
                                bytes.add(b)
                                try {
                                    val cmd = ByteArray(bytes.size)
                                    for (i in bytes.indices) {
                                        cmd[i] = bytes[i]
                                    }
                                    val baseDecoder = BaseDecoder(cmd)
                                    Log.i("mcu2dev:", baseDecoder.escapeBytesStr())
                                    CofarSDK.post2Dev(baseDecoder.baseBody)
                                    bytes.clear()
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                    Log.i("weilai-protocol", e.message!!)
                                    bytes.clear()
                                    bytes.add(b)
                                }
                            }
                        } else if (bytes.size != 0) {
                            bytes.add(b)
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Log.i("weilai-protocol", e.message!!)
            }
        }
    }
}