import { useEffect } from "react";
import { useProtocol } from "./useProtocol";
import Packet from "@/app/providers/ProtocolProvider/protocol/packet";

export const usePacket = (packetId : number, callback: (packet : any) => void, deps?: any[]) => {
    const {protocol} = useProtocol();

    const waitPacket = (packetId: number, callback: (packet: Packet) => void) : number => {
        return protocol.waitPacket(packetId, callback);
    };

    const unwaitPacket = (packetId: number, callback: (packet: Packet) => void) => {
        protocol.unwaitPacket(packetId, callback);
    };

    useEffect(() => {
        let unwait = (receivedPacket: Packet) => {
            callback(receivedPacket);
        };
        waitPacket(packetId, unwait);
        return () => {
            // Cleanup function to remove the packet listener
            unwaitPacket(packetId, unwait);
        };
    }, deps);
}