package com.rosetta.messenger.network

enum class DeviceState(val value: Int) {
    ONLINE(0),
    OFFLINE(1);

    companion object {
        fun fromValue(value: Int): DeviceState {
            return entries.firstOrNull { it.value == value } ?: OFFLINE
        }
    }
}

enum class DeviceVerifyState(val value: Int) {
    VERIFIED(0),
    NOT_VERIFIED(1);

    companion object {
        fun fromValue(value: Int): DeviceVerifyState {
            return entries.firstOrNull { it.value == value } ?: VERIFIED
        }
    }
}

data class DeviceEntry(
    val deviceId: String,
    val deviceName: String,
    val deviceOs: String,
    val deviceStatus: DeviceState,
    val deviceVerify: DeviceVerifyState
)

class PacketDeviceList : Packet() {
    var devices: List<DeviceEntry> = emptyList()

    override fun getPacketId(): Int = 0x17

    override fun receive(stream: Stream) {
        val deviceCount = stream.readInt16()
        val parsedDevices = mutableListOf<DeviceEntry>()
        repeat(deviceCount) {
            parsedDevices += DeviceEntry(
                deviceId = stream.readString(),
                deviceName = stream.readString(),
                deviceOs = stream.readString(),
                deviceStatus = DeviceState.fromValue(stream.readInt8()),
                deviceVerify = DeviceVerifyState.fromValue(stream.readInt8())
            )
        }
        devices = parsedDevices
    }

    override fun send(): Stream {
        val stream = Stream()
        stream.writeInt16(getPacketId())
        stream.writeInt16(devices.size)
        devices.forEach { device ->
            stream.writeString(device.deviceId)
            stream.writeString(device.deviceName)
            stream.writeString(device.deviceOs)
            stream.writeInt8(device.deviceStatus.value)
            stream.writeInt8(device.deviceVerify.value)
        }
        return stream
    }
}
