import Packet from "../packet";
import Stream from "../stream";
import { OnlineState } from "./packet.onlinestate";

export interface PacketSearchUser {
    username: string;
    title: string;
    publicKey: string;
    verified: number;
    online: OnlineState;
}

export class PacketSearch extends Packet {

    private privateKey : string = "";
    private search : string = "";
    private users : PacketSearchUser[] = [];


    public getPacketId(): number {
        return 0x03;
    }

    public _receive(stream: Stream): void {
        this.privateKey = stream.readString();
        this.search = stream.readString();
        const userCount = stream.readInt16();
        for (let i = 0; i < userCount; i++) {
            const username = stream.readString();
            const title = stream.readString();
            const publicKey = stream.readString();
            const verified = stream.readInt8();
            const online = stream.readInt8();
            this.users.push({ username, title, publicKey, online, verified });
        }
    }

    public _send(): Stream {
        const stream = new Stream();
        stream.writeInt16(this.getPacketId());
        stream.writeString(this.privateKey);
        stream.writeString(this.search);
        stream.writeInt16(this.users.length);
        for (const user of this.users) {
            stream.writeString(user.username);
            stream.writeString(user.title);
            stream.writeString(user.publicKey);
            stream.writeInt8(user.verified);
            stream.writeInt8(user.online);
        }
        return stream;
    }

    public getPrivateKey(): string {
        return this.privateKey;
    }

    public setPrivateKey(privateKey: string): void {
        this.privateKey = privateKey;
    }

    public getSearch(): string {
        return this.search;
    }

    public setSearch(search: string): void {
        this.search = search;
    }
    
    public addUser(searchUser: PacketSearchUser): void {
        this.users.push(searchUser);
    }

    public getUsers(): PacketSearchUser[] {
        return this.users;
    }
}