package com.adealink.weparty.hardware.resource

import com.adealink.weparty.hardware.Hardware
import com.adealink.weparty.hardware.HardwareClient
import com.adealink.weparty.hardware.HardwarePriority

abstract class HardwareResource(
    val hardware: Hardware, // 是否独占资源
    val isExclusive: Boolean,
) {
    @get:Synchronized
    var currentClient: HardwareClient? = null // 当前占用资源的客户端
        private set
    var currentClientPriority: HardwarePriority = HardwarePriority.HIGH //当前占用资源的优先级

    private var acquiredTime: Long = 0 // 获取时间戳

    @Synchronized
    fun acquire(client: HardwareClient): Boolean {
        if (!client.isActive()) {
            return false
        }
        if (isAvailable || (!isExclusive && currentClient?.clientId != client.clientId)) {
            currentClient = client
            acquiredTime = System.currentTimeMillis()
            return true
        }
        return false
    }

    @Synchronized
    fun release(clientId: String?): Boolean {
        if (currentClient != null && currentClient?.clientId == clientId) {
            currentClient = null
            acquiredTime = 0
            return true
        }
        return false
    }

    @get:Synchronized
    val isAvailable: Boolean
        get() = currentClient == null

    @get:Synchronized
    val holdDuration: Long
        get() = if (acquiredTime > 0) System.currentTimeMillis() - acquiredTime else 0 // 其他getter方法...

    abstract fun checkClientPermission(clientId: String): Boolean
}