package com.jihe.punchnet.data

import com.jihe.punchnet.api.NodeItem
import com.jihe.punchnet.api.ResourceItem
import com.jihe.punchnet.api.ExitNodeItem
import com.jihe.punchnet.api.ConnectResponseData
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

data class LocalProfileInfo(
    val ip: String,
    val maskLen: Int,
    val hostname: String,
    val identityId: Int
)

object NodeRepository {
    private val _nodes = MutableStateFlow<List<NodeItem>>(emptyList())
    val nodes: StateFlow<List<NodeItem>> = _nodes

    private val _resources = MutableStateFlow<List<ResourceItem>>(emptyList())
    val resources: StateFlow<List<ResourceItem>> = _resources

    private val _exitNodes = MutableStateFlow<List<ExitNodeItem>>(emptyList())
    val exitNodes: StateFlow<List<ExitNodeItem>> = _exitNodes

    private val _localProfile = MutableStateFlow<LocalProfileInfo?>(null)
    val localProfile: StateFlow<LocalProfileInfo?> = _localProfile

    fun updateAll(data: ConnectResponseData?) {
        if (data == null) {
            clear()
            return
        }
        _nodes.value = data.nodeList ?: emptyList()
        _resources.value = data.resourceList ?: emptyList()
        _exitNodes.value = data.exitNode ?: emptyList()
        _localProfile.value = LocalProfileInfo(
            ip = data.ip,
            maskLen = data.maskLen,
            hostname = data.hostname,
            identityId = data.identityId
        )
    }

    fun updateNodes(newNodes: List<NodeItem>?) {
        _nodes.value = newNodes ?: emptyList()
    }

    fun clear() {
        _nodes.value = emptyList()
        _resources.value = emptyList()
        _exitNodes.value = emptyList()
        _localProfile.value = null
    }
}
