package com.hboxs.serialport.plc.thread

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.hboxs.serialport.plc.SerialPortSendQueue
import com.quyunshuo.androidbaseframemvvm.base.addressenum.PlcParamAddressEnum
import com.hboxs.serialport.plc.frame.ReadCommandFrame
import com.hboxs.serialport.plc.frame.WriteCommandFrame
import com.hboxs.serialport.sbc.VboxSerialPortSendQueue
import com.hboxs.serialport.sbc.frame.VboxCommand
import com.hboxs.serialport.sbc.frame.VboxWriteCommand
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ThreadCloseReParam : LifecycleObserver {

    private val TAG = "ThreadCloseReParam"


    var jobWriteData: Job? = null
        get() = field

    var isActiveWriteData: Boolean = true
        get() = field
        set(value) {
            field = value
        }


    var jobdata20: Job? = null
        get() = field
    var isdata20: Boolean = true
        get() = field
        set(value) {
            field = value
        }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun startRead() {


    }

    public fun startData20() {
        closeData()
        jobdata20 = CoroutineScope(Dispatchers.Main).launch {
            while (isdata20) {
                Log.d("backinfo", "发送jobdata20")

                VboxSerialPortSendQueue.getInstance()
                    .sendCommand(
                        VboxWriteCommand(
                            VboxCommand.CMD_GETDATATWENTY,
                            "000000010001"
                        )
                    )
                // 执行定时任务的操作
                delay(500) // 每隔2秒重复执行
            }
        }
    }

    public fun closeData() {
        jobdata20?.cancel()
    }

    fun writeData(data: String) {
        closeWriteData()
        jobWriteData = CoroutineScope(Dispatchers.Main).launch {
            while (isActiveWriteData) {
                Log.d("backinfo","修改的数据："+data)

                VboxSerialPortSendQueue.getInstance()
                    .sendCommand(VboxWriteCommand(VboxCommand.CMD_WRITEDATATWENTY, data))
                delay(1000) // 每隔2秒重复执行
            }
        }
    }

    fun closeWriteData() {
        jobWriteData?.cancel()
    }


    /**
     * 关掉线程池
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun destroy() {
        //避免线程池关不掉
        closeData()
        closeWriteData()
    }


}