package com.rosetta.messenger.network.connection

import com.rosetta.messenger.network.DeviceEntry
import com.rosetta.messenger.network.DeviceResolveSolution
import com.rosetta.messenger.network.DeviceVerifyState
import com.rosetta.messenger.network.PacketDeviceList
import com.rosetta.messenger.network.PacketDeviceResolve
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class DeviceVerificationService {
    private val _devices = MutableStateFlow<List<DeviceEntry>>(emptyList())
    val devices: StateFlow<List<DeviceEntry>> = _devices.asStateFlow()

    private val _pendingDeviceVerification = MutableStateFlow<DeviceEntry?>(null)
    val pendingDeviceVerification: StateFlow<DeviceEntry?> = _pendingDeviceVerification.asStateFlow()

    fun handleDeviceList(packet: PacketDeviceList) {
        val parsedDevices = packet.devices
        _devices.value = parsedDevices
        _pendingDeviceVerification.value =
            parsedDevices.firstOrNull { device ->
                device.deviceVerify == DeviceVerifyState.NOT_VERIFIED
            }
    }

    fun buildResolvePacket(
        deviceId: String,
        solution: DeviceResolveSolution
    ): PacketDeviceResolve {
        return PacketDeviceResolve().apply {
            this.deviceId = deviceId
            this.solution = solution
        }
    }

    fun clear() {
        _devices.value = emptyList()
        _pendingDeviceVerification.value = null
    }
}
