import Foundation

enum DeviceState: Int {
    case online = 0
    case offline = 1
}

enum DeviceVerifyState: Int {
    case verified = 0
    case notVerified = 1
}

struct DeviceEntry {
    var deviceId: String
    var deviceName: String
    var deviceOs: String
    var deviceStatus: DeviceState
    var deviceVerify: DeviceVerifyState
}

/// Device list packet (0x17).
struct PacketDeviceList: Packet {
    static let packetId = 0x17

    var devices: [DeviceEntry] = []

    func write(to stream: Stream) {
        stream.writeInt16(devices.count)
        for device in devices {
            stream.writeString(device.deviceId)
            stream.writeString(device.deviceName)
            stream.writeString(device.deviceOs)
            stream.writeInt8(device.deviceStatus.rawValue)
            stream.writeInt8(device.deviceVerify.rawValue)
        }
    }

    mutating func read(from stream: Stream) {
        let count = stream.readInt16()
        var parsed: [DeviceEntry] = []
        parsed.reserveCapacity(max(0, count))
        for _ in 0..<count {
            parsed.append(
                DeviceEntry(
                    deviceId: stream.readString(),
                    deviceName: stream.readString(),
                    deviceOs: stream.readString(),
                    deviceStatus: DeviceState(rawValue: stream.readInt8()) ?? .offline,
                    deviceVerify: DeviceVerifyState(rawValue: stream.readInt8()) ?? .verified
                )
            )
        }
        devices = parsed
    }
}
