const fs = require("fs");
const path = require("path");
const { app, dialog } = require("electron");

class LockFileManager {
    constructor() {}

    // Function to check if a process with a given PID is running
    static isProcessRunning(pid) {
        try {
            // Sending signal 0 does not kill the process but checks if it exists
            process.kill(pid, 0);
            return true; // Process exists
        } catch (e) {
            return e.code === 'EPERM'; // EPERM means process exists but we don't have permission
        }
    }

    // Function to handle the lock file logic
    static handleLockFile(appId) {
        const lockFilePath = path.join(app.getPath("userData"), `${appId}.lock`);
        const currentPid = process.pid;

        // Check if lock file exists
        if (fs.existsSync(lockFilePath)) {
            try {
                const existingPid = parseInt(fs.readFileSync(lockFilePath, 'utf-8'));

                // Check if the process with the existing PID is running
                if (LockFileManager.isProcessRunning(existingPid)) {
                    // If the existing PID matches the current PID, it's likely a duplicate launch of the same instance
                    if (existingPid === currentPid) {
                        console.log(`Another instance of ${appId} with the same PID is already running.`);
                        // Prevent the new instance from opening
                        dialog.showErrorBox(
                            'Application Already Running',
                            `Another instance of "${appId}" is already running.`
                        );
                        app.quit();
                        return false; // Indicate that the app should not proceed
                    } else {
                        // Another instance is running with a different PID
                        console.log(`Another instance of ${appId} (PID: ${existingPid}) is already running.`);
                        dialog.showErrorBox(
                            'Application Already Running',
                            `Another instance of "${appId}" is already running.`
                        );
                        app.quit();
                        return false; // Indicate that the app should not proceed
                    }
                } else {
                    // The process with the PID in the lock file is not running,
                    // or the lock file contains an invalid PID. Overwrite it.
                    console.log(`Lock file found for ${appId} (PID: ${existingPid}), but process is not running. Overwriting.`);
                    fs.writeFileSync(lockFilePath, currentPid.toString());
                    return true; // Indicate that the app can proceed
                }
            } catch (e) {
                console.error(`Error reading or parsing lock file for ${appId}: ${e}`);
                // If there's an error reading the lock file, assume it's invalid and try to overwrite
                try {
                    fs.writeFileSync(lockFilePath, currentPid.toString());
                    return true; // Indicate that the app can proceed
                } catch (writeError) {
                    console.error(`Error writing lock file for ${appId}: ${writeError}`);
                    dialog.showErrorBox(
                        'Application Error',
                        `Could not create or update lock file for "${appId}". Please check file permissions.`
                    );
                    app.quit();
                    return false; // Indicate that the app should not proceed
                }
            }
        } else {
            // Lock file does not exist, create it
            console.log(`No lock file found for ${appId}. Creating new one.`);
            try {
                fs.writeFileSync(lockFilePath, currentPid.toString());
                return true; // Indicate that the app can proceed
            } catch (e) {
                console.error(`Error creating lock file for ${appId}: ${e}`);
                dialog.showErrorBox(
                    'Application Error',
                    `Could not create lock file for "${appId}". Please check file permissions.`
                );
                app.quit();
                return false; // Indicate that the app should not proceed
            }
        }
    }

    // Function to remove the lock file on app exit
    static removeLockFile(appId) {
        const lockFilePath = path.join(app.getPath("userData"), `${appId}.lock`);
        if (fs.existsSync(lockFilePath)) {
            try {
                fs.unlinkSync(lockFilePath);
                console.log(`Removed lock file for ${appId}`);
            } catch (e) {
                console.error(`Error removing lock file for ${appId}: ${e}`);
            }
        }
    }
}

module.exports = LockFileManager; 