package top.r3944realms.ltdmanager.dglab.manager

import com.r3944realms.dg_lab.manager.DGPBClientManager

class ClientManager(
    private val clients: MutableMap<String, DGPBClientManager> = mutableMapOf(),
) : IManager<MutableMap<String, DGPBClientManager>> {

    /**
     * 强度信息数据类
     */
    data class ClientStrengthInfo(
        val aValue: Int,
        val aMax: Int,
        val bValue: Int,
        val bMax: Int,
        val timestamp: Long = System.currentTimeMillis()
    ) {
        fun getAStrength(): Int = aValue
        fun getBStrength(): Int = bValue
        fun getAStrengthPercent(): Double = if (aMax > 0) (aValue.toDouble() / aMax) * 100 else 0.0
        fun getBStrengthPercent(): Double = if (bMax > 0) (bValue.toDouble() / bMax) * 100 else 0.0

        override fun toString(): String {
            return "A: $aValue/$aMax (${String.format("%.1f", getAStrengthPercent())}%), B: $bValue/$bMax (${String.format("%.1f", getBStrengthPercent())}%)"
        }
    }

    // 存储每个客户端的强度信息
    private val clientStrengths: MutableMap<String, ClientStrengthInfo> = mutableMapOf()

    // 存储每个客户端最后更新时间
    private val lastUpdateTime: MutableMap<String, Long> = mutableMapOf()

    /**
     * 获取客户端的强度信息
     * @param key 客户端标识
     * @return 强度信息，如果不存在则返回 null
     */
    fun getClientStrength(key: String): ClientStrengthInfo? {
        return clientStrengths[key]
    }

    /**
     * 更新客户端的强度信息
     * @param key 客户端标识
     * @param strengthInfo 强度信息
     */
    fun updateClientStrength(key: String, strengthInfo: ClientStrengthInfo) {
        clientStrengths[key] = strengthInfo
        lastUpdateTime[key] = System.currentTimeMillis()
    }

    /**
     * 添加单例客户端管理示例
     * @param key 唯一标识客户端管理的 key，比如 ID 或 name
     */
    fun addClient(key: String, client: DGPBClientManager) {
        clients[key] = client
    }

    /**
     * 移除单例客户端管理实例
     */
    fun removeClient(key: String) {
        clients.remove(key)?.stop()
        clientStrengths.remove(key)
        lastUpdateTime.remove(key)
    }

    /**
     * 根据 key 获取客户端
     */
    fun getClient(key: String): DGPBClientManager? {
        return clients[key]
    }

    /**
     * 启动所有客户端
     */
    override fun startAll() {
        clients.values.forEach { it.start() }
    }

    /**
     * 停止所有客户端
     */
    override fun stopAll() {
        clients.values.forEach { it.stop() }
        clients.clear()
    }

    /**
     * 获取内部 Map 实例
     */
    override fun getInstance(): MutableMap<String, DGPBClientManager> {
        return clients
    }
}
