

export class Telemetry {
    constructor(program, logger, services, options) {
        this.program = program;
        this.logger = logger;
        services['telemetry'] = this;
        this.telemetryEndpoint = options.telemetryEndpoint;
        this.userId = options.userId;
        this.enabled = (options.enabled!==undefined?options.enabled:true);
    }

    enable() {
        this.logger.debug('Telemetry.enable');
        this.enabled = true;
    }
    disable() {
        this.logger.debug('Telemetry.disable');
        this.enabled = false;
    }

    sendTelemetry(commandName, subCommand, params) {
        this.logger.debug('Telemetry.sendTelemetry');
        if (this.enabled) {
            const data = {
                command: commandName,
                subcommand: subCommand,
                parameters: params,
                timestamp: new Date().toISOString(),
                userId: this.userId
            };

            this.logger.debug(`telemetryEndpoint: ${this.telemetryEndpoint}`);
            // Envoyer la requête de manière non bloquante
            fetch(this.telemetryEndpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            }).catch(err => {
                // Gérer les erreurs en silence, pour ne pas interrompre le flux utilisateur
                console.error('Failed to send telemetry:', err);
            });
        }
    }
}


// Appel à la fonction
// Dans votre code qui exécute la commande `mon_outil categorie sous-commande --param`
//const params = { param1: 'valeur', param2: 'valeur' };
//sendTelemetry('categorie', 'sous-commande', params);