import { rpc } from '../../core/rpc/index';
import { PlayerWrapper } from '../../core/player/player-registry';

// Replaces RageMP player.callProc() with our FiveM RPC module.
export async function CallProcRetry(player: PlayerWrapper, event: string, args: any[] = []): Promise<any> {
    const maxTries = 10;
    let tries = 0;
    let lastError: any;

    do {
        try {
            return await rpc.callClient(player, event, ...args);
        } catch (error) {
            tries++;
            lastError = error;
            if (tries < maxTries) {
                await new Promise((resolve) => setTimeout(resolve, 100 * tries));
            }
        }
    } while (tries < maxTries);

    throw {
        message: `Failed CallProcRetry after ${tries} tries`,
        error: lastError,
        details: { event, args },
    };
}
