import { useState } from "react";
import { useProtocol } from "../ProtocolProvider/useProtocol";
import { PacketSearch, PacketSearchUser } from "../ProtocolProvider/protocol/packets/packet.search";
import { usePrivateKeyHash } from "../AccountProvider/usePrivateKeyHash";

export function useSearch() : [
    PacketSearchUser[],
    (username : string) => void,
    React.Dispatch<React.SetStateAction<PacketSearchUser[]>>
] {
    const {protocol} = useProtocol();
    const [searchResults, setSearchResults] = useState<PacketSearchUser[]>([]);
    const privateKeyHash = usePrivateKeyHash();

    protocol.waitPacketOnce(0x03, (packet : PacketSearch) => {
        setSearchResults(packet.getUsers());
    });

    const search = (username : string) => {
        let packet = new PacketSearch();
        packet.setSearch(username);
        packet.setPrivateKey(privateKeyHash);
        protocol.sendPacket(packet);
    }

    return [
        searchResults,
        search,
        setSearchResults
    ];
}