package com.rosetta.messenger.network

/**
 * Public key with online state
 */
data class PublicKeyOnlineState(
    val publicKey: String,
    val state: OnlineState
)

/**
 * Online State packet (ID: 0x05)
 * Notify about user online status
 * Формат как в React Native: массив {publicKey, state}
 */
class PacketOnlineState : Packet() {
    var publicKeysState: MutableList<PublicKeyOnlineState> = mutableListOf()

    override fun getPacketId(): Int = 0x05

    override fun receive(stream: Stream) {
        val count = stream.readInt8()
        publicKeysState.clear()
        repeat(count) {
            val publicKey = stream.readString()
            val isOnline = stream.readBoolean()
            publicKeysState.add(PublicKeyOnlineState(publicKey, OnlineState.fromBoolean(isOnline)))
        }
    }

    override fun send(): Stream {
        val stream = Stream()
        stream.writeInt16(getPacketId())
        stream.writeInt8(publicKeysState.size)
        publicKeysState.forEach { item ->
            stream.writeString(item.publicKey)
            stream.writeBoolean(item.state == OnlineState.ONLINE)
        }
        return stream
    }
}
