const { exec } = require('child_process');
const path = require('path');

class XrayStarter {
    constructor() {
        this.command = './xray';
        this.cwd = '/usr/local/x-ui';
    }


    isProcessRunning(configName) {
        return new Promise((resolve) => {
            const searchCommand = `sudo ps aux | grep "${configName}" | grep -v grep`;
            exec(searchCommand, (error, stdout) => {
                if (stdout) {
                    console.log('Process',configName,'found')
                    resolve(true);  // Process found
                } else {
                    console.log('Process',configName,'not found')
                    resolve(false); // Process not found
                }
            });
        });
    }

    killProcesses(configName) {
        return new Promise((resolve, reject) => {
            const killCommand = `sudo pkill -f "${configName}"`;
            exec(killCommand, (error) => {
                if (error) {
                    reject(`Error killing processes for ${configName}: ${error.message}`);
                } else {
                    resolve();
                }
            });
        });
    }

    async restart(configName) {
        try {

               // console.log(`Xray process for ${configName} is already running. Killing it...`);
                await this.killProcesses(configName);
              //  console.log(`Killed processes for ${configName}.`);


           // console.log(`Restarted Xray process for ${configName} in the background.`);
        } catch (error) {
            console.error(`Error while restarting Xray process for ${configName}: ${error}`);
        }


        await this.start(configName);
        console.log('Service Restarted')
    }


    start(configName) {
       // const configFilePath = path.join(this.cwd, configName);

        // Start Xray in the background and silently using exec

        let  commandStr = `cd /usr/local/x-ui/  && sudo  ./xray run -c ${configName} > /dev/null 2>&1 &`;

        if (configName ==='config1000.json')
              commandStr = `sudo /usr/local/x-ui/xray2 run -c ${configName} > /dev/null 2>&1 &`;
        exec(commandStr, { cwd: this.cwd }, (error) => {
            if (error) {
                console.error(`Error starting Xray process: ${error.message}`);
            } else {
                console.log(`Started Xray process for ${configName} in the background.`);
            }
        });
    }
}



module.exports = XrayStarter;