import Foundation

// MARK: - HandshakeState

enum HandshakeState: Int {
    case completed = 0
    case needDeviceVerification = 1

    init(value: Int) {
        self = HandshakeState(rawValue: value) ?? .completed
    }
}

// MARK: - HandshakeDevice

struct HandshakeDevice {
    var deviceId: String = ""
    var deviceName: String = ""
    var deviceOs: String = ""
}

// MARK: - PacketHandshake (0x00)

struct PacketHandshake: Packet {
    static let packetId = 0x00

    var privateKey: String = ""       // SHA256(privateKey + "rosetta")
    var publicKey: String = ""        // Compressed secp256k1 public key (hex)
    var protocolVersion: Int = 1
    var heartbeatInterval: Int = 15
    var device = HandshakeDevice()
    var handshakeState: HandshakeState = .needDeviceVerification

    func write(to stream: Stream) {
        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.rawValue)
    }

    mutating func read(from 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(value: stream.readInt8())
    }
}
