package com.casic.common.detector.gd.service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import com.casic.common.detector.gd.base.BaseApplication
import com.casic.common.detector.gd.callback.OnSerialPortListener
import com.casic.common.detector.gd.utils.GpioManager
import java.io.IOException
import java.util.concurrent.Executors

class SerialPortService : Service() {

    private val kTag = "SerialPortService"
    private val gpioManager by lazy { GpioManager() }
    private val serialPorts = BaseApplication.get().getSerialPorts()
    private var executor = Executors.newFixedThreadPool(2) //创建一个固定大小的线程池，可控制线程最大并发数，超出的线程会在队列中等待

    /**
     * 读取数据 1
     * 暂停读取 0
     * */
    private var gpioState = 0

    fun openSerialPort(commandArray: ArrayList<Char>, listener: OnSerialPortListener) {
        //调高串口电位
        gpioManager.setGpioHigh("18")
        gpioState = 1
        Log.d(kTag, "openSerialPort: 调高串口电位")

        Thread.sleep(100)

        val outputStream = serialPorts.first().outputStream
        commandArray.forEach {
            outputStream.write(it.code)
            outputStream.flush()
            Thread.sleep(50)
        }

        executor.execute {
            //读
            while (gpioState == 1) {
                try {
                    val byteArray = ByteArray(32)
                    val size = serialPorts.first().inputStream.read(byteArray)
                    if (size > 0) {
                        listener.onDataReceived(byteArray)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }

        executor.execute {
            //读
            while (gpioState == 1) {
                try {
                    val byteArray = ByteArray(16)
                    val size = serialPorts.last().inputStream.read(byteArray)
                    if (size > 0) {
                        listener.onDataReceived(byteArray)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    fun closeSerialPort() {
        //降低串口电位
        gpioManager.setGpioLow("18")
        gpioState = 0
        Log.d(kTag, "closeSerialPort: 降低串口电位")
    }

    override fun onBind(intent: Intent?): IBinder {
        return ServiceBinder()
    }

    inner class ServiceBinder : Binder() {
        fun getSerialPortService(): SerialPortService {
            return this@SerialPortService
        }
    }
}