package com.rosetta.messenger.network

enum class HandshakeState(val value: Int) {
    COMPLETED(0),
    NEED_DEVICE_VERIFICATION(1);

    companion object {
        fun fromValue(value: Int): HandshakeState {
            // Fail-safe: unknown value must not auto-authenticate.
            return entries.firstOrNull { it.value == value } ?: NEED_DEVICE_VERIFICATION
        }
    }
}

data class HandshakeDevice(
    var deviceId: String = "",
    var deviceName: String = "",
    var deviceOs: String = ""
)

/**
 * Handshake packet (ID: 0x00)
 * First packet sent by client to authenticate with the server
 */
class PacketHandshake : Packet() {
    var privateKey: String = ""
    var publicKey: String = ""
    var protocolVersion: Int = 1
    var heartbeatInterval: Int = 15
    var device: HandshakeDevice = HandshakeDevice()
    var handshakeState: HandshakeState = HandshakeState.NEED_DEVICE_VERIFICATION

    override fun getPacketId(): Int = 0x00

    override fun receive(stream: Stream) {
        privateKey = stream.readString()
        publicKey = stream.readString()
        protocolVersion = stream.readInt8()
        heartbeatInterval = stream.readInt8()
        device = HandshakeDevice(
            deviceId = stream.readString(),
            deviceName = stream.readString(),
            deviceOs = stream.readString()
        )
        handshakeState = HandshakeState.fromValue(stream.readInt8())
    }

    override fun send(): Stream {
        val stream = Stream()
        stream.writeInt16(getPacketId())
        stream.writeString(privateKey)
        stream.writeString(publicKey)
        stream.writeInt8(protocolVersion)
        stream.writeInt8(heartbeatInterval)
        stream.writeString(device.deviceId)
        stream.writeString(device.deviceName)
        stream.writeString(device.deviceOs)
        stream.writeInt8(handshakeState.value)
        return stream
    }
}
