"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.eventManager = void 0;
const child_process_1 = require("child_process");
const os = require("os");
const path = require("path");
const cli_ux_1 = require("cli-ux");
const checkXDGInstalled = () => {
    return new Promise((resolve, reject) => {
        (0, child_process_1.exec)("which xdg-open", (error, stdout, stderr) => {
            if (error) {
                resolve(false);
            }
            if (stdout) {
                resolve(true);
            }
            else {
                resolve(false);
            }
        });
    });
};
const openFile = (filePath) => {
    const fullPath = path.join(process.cwd(), filePath);
    let command;
    switch (os.platform()) {
        case "darwin": // macOS
            command = `open ${fullPath}`;
            break;
        case "win32": // Windows
            command = `start ${fullPath}`;
            break;
        case "linux": // Linux
            command = `xdg-open ${fullPath}`;
            break;
        default:
            throw new Error("Unsupported OS");
    }
    (0, child_process_1.exec)(command, (error, stdout, stderr) => {
        if (error) {
            console.error(`exec error: ${error}`);
        }
    });
};
const eventManager = {
    enqueue: (event, data) => {
        if (event === "start_exercise") {
            const exercise = data;
            const filesToOpen = exercise.files
                .filter((file) => !file.hidden)
                .map((file) => {
                return file.path.replace("\\", "/");
            });
            for (const file of filesToOpen) {
                openFile(file);
            }
        }
        if (event === "open_files") {
            const files = data;
            for (const file of files) {
                const correctedPath = file.replace("\\", "/");
                openFile(correctedPath);
            }
        }
        if (event === "open_window") {
            const url = data.url;
            cli_ux_1.default.open(url);
        }
    },
    checkXDGInstalled,
};
exports.eventManager = eventManager;
