const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const si = require('systeminformation');
const fs = require('fs');
const os = require('os');

let mainWindow;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 900,
        height: 700,
        minWidth: 800,
        minHeight: 600,
        frame: false,
        transparent: true,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        },
        icon: path.join(__dirname, 'icon.png')
    });

    mainWindow.loadFile('index.html');
    // mainWindow.webContents.openDevTools(); // Para debug
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
});

// Obtener toda la información del sistema
ipcMain.handle('get-system-info', async () => {
    try {
        const [cpu, mem, disk, graphics, motherboard, bios, osInfo, network, networkInterfaces] = await Promise.all([
            si.cpu(),
            si.mem(),
            si.diskLayout(),
            si.graphics(),
            si.baseboard(),
            si.bios(),
            si.osInfo(),
            si.networkInterfaces(),
            si.networkGatewayDefault()
        ]);

        // Obtener IP y segmento
        const activeNet = network.find(n => n.ip4 && n.ip4 !== '127.0.0.1' && !n.internal) || network[0];

        // Obtener grupo de trabajo (Windows - usando PowerShell)
        let workgroup = 'N/A';
        try {
            const { execSync } = require('child_process');
            const netInfo = execSync('powershell -Command "(Get-WmiObject Win32_ComputerSystem).Workgroup"', { encoding: 'utf8' });
            workgroup = netInfo.trim() || 'WORKGROUP';
        } catch (e) {
            workgroup = 'WORKGROUP';
        }

        // Fecha de instalación del SO (Windows - usando PowerShell)
        let installDate = 'N/A';
        try {
            const { execSync } = require('child_process');
            const installInfo = execSync('powershell -Command "(Get-CimInstance Win32_OperatingSystem).InstallDate.ToString(\'dd/MM/yyyy\')"', { encoding: 'utf8' });
            installDate = installInfo.trim() || 'N/A';
        } catch (e) { }

        return {
            cpu: {
                manufacturer: cpu.manufacturer,
                brand: cpu.brand,
                speed: cpu.speed,
                cores: cpu.cores,
                physicalCores: cpu.physicalCores
            },
            memory: {
                total: (mem.total / (1024 ** 3)).toFixed(2) + ' GB',
                used: (mem.used / (1024 ** 3)).toFixed(2) + ' GB',
                free: (mem.free / (1024 ** 3)).toFixed(2) + ' GB'
            },
            disks: disk.map(d => ({
                name: d.name || d.device,
                type: d.type,
                size: (d.size / (1024 ** 3)).toFixed(2) + ' GB',
                vendor: d.vendor,
                model: d.name
            })),
            graphics: graphics.controllers.map(g => ({
                model: g.model,
                vendor: g.vendor,
                vram: g.vram ? g.vram + ' MB' : 'N/A'
            })),
            motherboard: {
                manufacturer: motherboard.manufacturer,
                model: motherboard.model,
                serial: motherboard.serial
            },
            bios: {
                vendor: bios.vendor,
                version: bios.version,
                releaseDate: bios.releaseDate
            },
            os: {
                platform: osInfo.platform,
                distro: osInfo.distro,
                release: osInfo.release,
                arch: osInfo.arch,
                hostname: os.hostname(),
                installDate: installDate
            },
            network: {
                interface: activeNet?.iface || 'N/A',
                type: activeNet?.type || 'N/A',
                ip: activeNet?.ip4 || 'N/A',
                subnet: activeNet?.ip4subnet || 'N/A',
                mac: activeNet?.mac || 'N/A',
                speed: activeNet?.speed ? activeNet.speed + ' Mbps' : 'N/A'
            },
            workgroup: workgroup,
            timestamp: new Date().toLocaleString('es-CO')
        };
    } catch (error) {
        console.error('Error getting system info:', error);
        return { error: error.message };
    }
});

// Exportar a TXT
ipcMain.handle('export-txt', async (event, data) => {
    const { filePath } = await dialog.showSaveDialog({
        title: 'Exportar a TXT',
        defaultPath: `ForyHardware_${Date.now()}.txt`,
        filters: [{ name: 'Text Files', extensions: ['txt'] }]
    });

    if (filePath) {
        fs.writeFileSync(filePath, data, 'utf8');
        return { success: true, path: filePath };
    }
    return { success: false };
});

// Exportar a JPG
ipcMain.handle('export-jpg', async (event, imageData) => {
    const { filePath } = await dialog.showSaveDialog({
        title: 'Exportar a JPG',
        defaultPath: `ForyHardware_${Date.now()}.jpg`,
        filters: [{ name: 'JPEG Image', extensions: ['jpg'] }]
    });

    if (filePath) {
        const base64Data = imageData.replace(/^data:image\/\w+;base64,/, '');
        fs.writeFileSync(filePath, Buffer.from(base64Data, 'base64'));
        return { success: true, path: filePath };
    }
    return { success: false };
});

// Control de ventana
ipcMain.on('window-minimize', () => mainWindow.minimize());
ipcMain.on('window-maximize', () => {
    if (mainWindow.isMaximized()) {
        mainWindow.unmaximize();
    } else {
        mainWindow.maximize();
    }
});
ipcMain.on('window-close', () => mainWindow.close());
