package com.abbidot.tracker.vm

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abbidot.tracker.util.SocketUtilManage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/**
 *Created  by .yzq on 2025/4/21/021.
 * @link
 * @description:
 */
class SocketSendMessageViewModel : ViewModel() {

    //线程同步锁
    private val mMutex = Mutex()
    private var mSocketUtilManage: SocketUtilManage? = null

    /**
     * 发送一个的消息，
     */
    fun sendCmd(
        socketUtilManage: SocketUtilManage, mac: String, msgID: Byte, msgData: MutableList<Byte>
    ) {
        viewModelScope.launch(Dispatchers.IO) {
            mMutex.withLock {
                mSocketUtilManage = socketUtilManage.apply {
                    sendMessage(mac, msgID, msgData)
                }
                delay(2000)
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        mSocketUtilManage?.destroy()
    }
}