import Foundation

/// Search packet (0x03) — search for users by username or public key.
struct PacketSearch: Packet {
    static let packetId = 0x03

    var privateKey: String = ""
    var search: String = ""
    var users: [SearchUser] = []

    func write(to stream: Stream) {
        stream.writeString(privateKey)
        stream.writeString(search)
        // Must write users count (0) — server's receive() always reads it
        stream.writeInt16(users.count)
        for user in users {
            stream.writeString(user.username)
            stream.writeString(user.title)
            stream.writeString(user.publicKey)
            stream.writeInt8(user.verified)
            stream.writeInt8(user.online)
        }
    }

    mutating func read(from stream: Stream) {
        privateKey = stream.readString()
        search = stream.readString()
        let userCount = max(stream.readInt16(), 0)
        var list: [SearchUser] = []
        for _ in 0..<userCount {
            list.append(SearchUser(
                username: stream.readString(),
                title: stream.readString(),
                publicKey: stream.readString(),
                verified: stream.readInt8(),
                online: stream.readInt8()
            ))
        }
        users = list
    }
}
