"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileHelper = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const child_process_1 = require("child_process");
const logger_1 = require("../../utils/logger");
const path_2 = require("../../utils/path");
class FileHelper {
    logger = logger_1.Logger.getInstance();
    removeComponent(name) {
        this.logger.debug(`Removing component ${name}...`);
        const componentDir = (0, path_1.join)(path_2.PathUtils.getComponentDir(name));
        if ((0, fs_1.existsSync)(componentDir)) {
            (0, fs_1.rmSync)(componentDir, { recursive: true, force: true });
            this.logger.debug(`Component ${name} removed successfully from ${componentDir}`);
        }
        else {
            this.logger.debug(`Component directory ${componentDir} does not exist, nothing to remove.`);
        }
    }
    async storeComponent(component) {
        try {
            this.logger.debug(`Storing component ${component.name}...`);
            // Create temp directory for storing the downloaded file
            const tempDir = (0, path_1.join)(process.cwd(), 'temp');
            if (!(0, fs_1.existsSync)(tempDir)) {
                (0, fs_1.mkdirSync)(tempDir, { recursive: true });
            }
            // Write the file to temp location            
            const tempFilePath = (0, path_1.join)(tempDir, component.filename);
            this.logger.debug(`Writing component file to temp directory: ${tempDir}, data length: ${component.data.length}`);
            (0, fs_1.writeFileSync)(tempFilePath, component.data);
            this.logger.debug(`Component file written to ${tempFilePath}`);
            // Create components directory structure
            const componentsDir = (0, path_1.join)(process.cwd(), 'components');
            const componentDir = (0, path_1.join)(componentsDir, component.name);
            // Remove existing component directory if it exists
            if ((0, fs_1.existsSync)(componentDir)) {
                this.logger.debug(`Removing existing component directory: ${componentDir}`);
                (0, fs_1.rmSync)(componentDir, { recursive: true, force: true });
            }
            // Create fresh component directory
            (0, fs_1.mkdirSync)(componentDir, { recursive: true });
            // Extract based on file type
            const filename = component.filename.toLowerCase();
            if (filename.endsWith('.dmg')) {
                await this.extractDmg(tempFilePath, componentDir);
            }
            else if (filename.endsWith('.zip')) {
                await this.extractZip(tempFilePath, componentDir);
            }
            else {
                // For other files (like .exe), just copy them directly
                const targetPath = (0, path_1.join)(componentDir, component.filename);
                (0, fs_1.writeFileSync)(targetPath, component.data);
                this.logger.debug(`Copied ${component.filename} to ${componentDir}`);
            }
            this.logger.debug(`Removing temporary file: ${tempFilePath}`);
            // Clean up temp file
            // rmSync(tempFilePath, { force: true });
            this.logger.debug(`Temporary file ${tempFilePath} removed.`);
            this.logger.debug(`Component ${component.name} stored and extracted to ${componentDir} successfully!`);
            return componentDir;
        }
        catch (error) {
            this.logger.error(`Failed to store component ${component.name}:`, error);
            throw error;
        }
    }
    async extractDmg(dmgPath, extractDir) {
        try {
            // Create extraction directory
            if (!(0, fs_1.existsSync)(extractDir)) {
                (0, fs_1.mkdirSync)(extractDir, { recursive: true });
            }
            // Mount the DMG to a temporary location
            const mountPoint = `/tmp/dmg_mount_${Date.now()}`;
            (0, child_process_1.execSync)(`hdiutil attach "${dmgPath}" -mountpoint "${mountPoint}" -quiet`);
            // Copy contents to extraction directory
            (0, child_process_1.execSync)(`cp -R "${mountPoint}"/* "${extractDir}"/`);
            // Unmount the DMG
            (0, child_process_1.execSync)(`hdiutil detach "${mountPoint}" -quiet`);
            this.logger.debug(`Extracted DMG to ${extractDir}`);
        }
        catch (error) {
            this.logger.error(`Failed to extract DMG: ${error}`);
            throw error;
        }
    }
    async extractZip(zipPath, extractDir) {
        try {
            // Create extraction directory
            if (!(0, fs_1.existsSync)(extractDir)) {
                this.logger.debug(`Creating extraction directory: ${extractDir}`);
                (0, fs_1.mkdirSync)(extractDir, { recursive: true });
            }
            // Use built-in unzip on macOS/Linux or try different methods
            const platform = process.platform;
            if (platform === 'darwin' || platform === 'linux') {
                // Use unzip command on Unix systems
                const command = `unzip -q "${zipPath}" -d "${extractDir}"`;
                this.logger.debug(`Executing command: ${command}`);
                (0, child_process_1.execSync)(command);
            }
            else if (platform === 'win32') {
                // Use PowerShell Expand-Archive on Windows
                const command = `powershell -command "Expand-Archive -Path '${zipPath}' -DestinationPath '${extractDir}'  -Force"`;
                this.logger.debug(`Executing command: ${command}`);
                (0, child_process_1.execSync)(command);
            }
            else {
                throw new Error(`Unsupported platform for ZIP extraction: ${platform}`);
            }
            this.logger.debug(`Extracted ZIP to ${extractDir}`);
        }
        catch (error) {
            this.logger.error(`Failed to extract ZIP: ${error}`);
            throw error;
        }
    }
}
exports.FileHelper = FileHelper;
//# sourceMappingURL=file.helper.js.map