const { app, BrowserWindow, Menu, dialog, ipcMain, desktopCapturer, Notification, ipcRenderer, protocol, session } = require('electron');
const { autoUpdater } = require('electron-updater');
const os = require('os');
const pie = require("puppeteer-in-electron")
const puppeteer = require("puppeteer-core");
const path = require('path');
const https = require('https');
const axios = require('axios');
const $ = require('jquery');
const fs = require('fs');
const argv = require('yargs').argv;
const { exec } = require('child_process');
const { rr } = require('./rr');
const { HttpsProxyAgent } = require('https-proxy-agent');

app.disableHardwareAcceleration();

const logsDir = 'C:/RpaClaro';
const app_version = app.getVersion();
let url_platform = '';
let username = '';
let password = '';
let xpath_username = '';
let xpath_password = '';
let xpath_button = '';
let data_apps;
let okanToken;
let splashWindow;
let mainWindow;
let windowNew;
let browser;
let page;
let data_apps_user = [];
let appsOkan;
let appHtml;
let userDataApps;
let from_okan = false;


const CONFIG = {
    ENDPOINT_URL_APPS: 'https://rpa8dev.okan.tools/users/apps/byUserAdOrDocument',
    ENDPOINT_URL_APP: 'https://rpa8dev.okan.tools/app',
    ENDPOINT_OKAN_TOKEN: 'https://io.okan.tools/api/auth/electron',
    TOKEN_OKAN_USER: 'HrZTvmBNyQaM6jPI7sHo5ywN35ht/cplIBFeE+4Ufx8=',
    PROXY: 'http://proxyop.bop.local:8080',
    ENDPOINT_GET_PROFILE: 'https://io.okan.tools/api/auth/users/electron',
    ENDPOINT_GET_APPS: 'https://adm.okan.tools/wp-json/okanapiwp/v1/aplicativos/'
};

app.disableHardwareAcceleration();

pie.initialize(app);

const agent = new HttpsProxyAgent(CONFIG.PROXY);

const setupLogging = async () => {
    console.log(">> Iniciando configuracion de logs..");
    if (!fs.existsSync(logsDir)) {
        fs.mkdirSync(logsDir, { recursive: true });
    }
    const logFilePath = path.join(logsDir, 'console-log.txt');

    // Limpia el archivo de logs al inicio
    await fs.promises.writeFile(logFilePath, '', 'utf-8');
    // Helper para escribir logs en el archivo
    const writeLogToFile = (message) => {
        const now = new Date();
        const timestamp = now.toLocaleString('en-US', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: true
        }).replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');
        fs.appendFileSync(logFilePath, `[${timestamp}] ${message}\n`);
    };
    // Sobrescribe métodos de console
    ['log', 'info', 'warn', 'error'].forEach((method) => {
        const originalMethod = console[method];
        console[method] = (...args) => {
            const message = args
                .map((arg) => (typeof arg === 'object' ? JSON.stringify(arg, null, 2) : arg))
                .join(' ');
            writeLogToFile(message);
            originalMethod.apply(console, args); // Mantén la salida en la consola
        };
    });
};

async function getOkanToken() {
    try {
        const responseOkan = await axios.post(CONFIG.ENDPOINT_OKAN_TOKEN, { user: process.env.USUARIO }, {
            headers: { 'Authorization': CONFIG.TOKEN_OKAN_USER },
            httpsAgent: agent
        });
        if (responseOkan.data.cod == '0') {
            console.log('>> Token de Okan obtenido.');
            return responseOkan.data.data;
        } else {
            console.log('>> Error al obtener el token de Okan.');
            return null;
        }
    } catch (error) {
        console.log('>> Error en la petición del token de Okan:', error);
        await dialog.showMessageBox({
            type: 'error',
            defaultId: 0,
            title: 'Error de acceso',
            message: 'Error al comunicarse con Okan',
        });
        app.quit();
        return null;
    }
}

const processArguments = async () => {
    console.log(argv);
    process.env.MODE = 'prod';
    let url_okan = argv['_'];
    let code_okan_str = url_okan.toString();

    // Handle OKAN code from URL or direct argument
    if (argv['_'] && !argv.dev) {

        let code_okan = code_okan_str.split('&')[0].replace('rpaclaro:///?code=', '');
        let user_okan = code_okan_str.split('&')[1].replace('user=', '');
        process.env.OKAN = code_okan;
        process.env.USUARIO = user_okan;
        from_okan = true;
    } else {
        process.env.OKAN = argv.code;
        process.env.USUARIO = argv.user;
    }

    // Set environment mode
    if (argv.dev) {
        process.env.MODE = 'dev';
    } else {
        process.env.MODE = 'prod';
    }

    console.log('>> Iniciando RpaClaro..');
    console.log('_____________________________');
    console.log('RPA CLARO');
    console.log('Usuario: ' + process.env.USUARIO);
    console.log('Version: ' + app_version);
    console.log('Modo: ' + process.env.MODE);
    console.log('_____________________________');
};

const setupProtocolClient = async () => {
    if (process.defaultApp) {
        if (process.argv.length >= 2) {
            app.setAsDefaultProtocolClient('RpaClaro', process.execPath, [path.resolve(process.argv[1])])
        }
    } else {
        app.setAsDefaultProtocolClient('RpaClaro')
    }
    console.log('>> Configuracion de protocolos establecida.');
}

const copyFilesFromRR = () => {
    const origen = path.join(__dirname, 'rr');
    fs.readdir(origen, (err, archivos) => {
        if (err) {
            console.error('Error al leer el directorio de origen:', err);
            return;
        }
        archivos.forEach((archivo) => {
            const archivoOrigen = path.join(origen, archivo);
            const archivoDestino = path.join(logsDir, archivo);

            // Copia el archivo al directorio de destino
            fs.copyFile(archivoOrigen, archivoDestino, (err) => {
                if (err) {
                    console.error(`Error al copiar ${archivo}:`, err);
                } else {
                    // console.log(`${archivo} copiado correctamente.`);
                }
            });
        });
        console.log('>> Archivos copiados correctamente.');
    });
};

async function getOkanToken() {
    try {
        const responseOkan = await axios.post(CONFIG.ENDPOINT_OKAN_TOKEN, { user: process.env.USUARIO }, { headers: { 'Authorization': CONFIG.TOKEN_OKAN_USER } });
        if (responseOkan.data.cod == '0') {
            console.log('>> Token de Okan obtenido.');
            return responseOkan.data.data;
        } else {
            console.log('>> Error al obtener el token de Okan.');
            return null;
        }
    } catch (error) {
        console.log('>> Error en la petición del token de Okan:', error);
        await dialog.showMessageBox({
            type: 'error',
            defaultId: 0,
            title: 'Error de acceso',
            message: 'Error al comunicarse con Okan',
        });
        app.quit();
        return null;
    }
}

async function getProfile(token) {
    const token_okan = 'Bearer ' + token;

    try {
        const responseGetProfile = await axios.get(CONFIG.ENDPOINT_GET_PROFILE, { headers: { 'Authorization': token_okan } });
        if (responseGetProfile.data.cod == '0') {
            documento = responseGetProfile.data.data.document_number;
            profile = responseGetProfile.data.data.profile.id;
            console.log('>> Perfil: ' + profile);
            return profile;
        }
    } catch (e) {
        console.log('>> No se pudo obtener el perfil: ' + e);
    }
}

async function getApps(data_apps_user) {
    try {

        const urlAplicativos = CONFIG.ENDPOINT_GET_APPS + `${documento}/${profile}`;
        const responseAplicativos = await axios.get(urlAplicativos, { headers: { "Accept": "*/*", "Content-Type": "application/json" } });

        var apps_okan = [];
        if (responseAplicativos.data['cod'] == '0') {

            const new_apps = responseAplicativos.data['data']
                .filter(element => element['nombre_app'].startsWith('RPA'))
                .sort((a, b) => a.nombre_app.localeCompare(b.nombre_app));

            console.log('>> Aplicativos Okan: ' + new_apps.length);

            // Process each app from new_apps
            for (const app of new_apps) {
                let code = app.url.replace('rpaclaro://?code=', '');
                code = code.replace('RpaClaro://?code=', '');
                code = code.replace('&user={user}', '');
                let appExists = data_apps_user.desk?.some(deskApp => deskApp.code === code) || data_apps_user.web?.some(webApp => webApp.code === code);

                const appInfo = {
                    nombre_app: app.nombre_app,
                    code_app: code,
                    logo: app.logo,
                    status: appExists,
                    status_integrado: appExists ? 'integrado' : 'no_integrado',
                };

                apps_okan.push(appInfo);

                // Generate HTML for all apps at once using map and join
                appHtml = apps_okan.map(app => `
                    <div class="col-3 col-md-3 col-xl-3 shortcut app_click ${app.status_integrado}" 
                        name_app="${app.nombre_app}" 
                        integrado="${app.status}" 
                        code="${app.code_app}">
                        <div class="card border-none text-center">
                            <div class="card-body hp-knowledge-basic-card">
                                <img src="${app.logo}" class="logo">
                                <h5>${app.nombre_app}</h5>
                            </div>
                        </div>
                    </div>
                `).join('');
            }

            return appHtml;
        }
    } catch (e) {
        console.log('>> Error al obtener aplicaciones:' + e);
    }
}

async function getNetworkInfo() {
    const interfaces = os.networkInterfaces();
    let ipAddress = '';
    let macAddress = '';

    // Buscar en todas las interfaces de red
    for (const name of Object.keys(interfaces)) {
        for (const net of interfaces[name]) {
            // Buscar IPv4 y no localhost
            if (net.family === 'IPv4' && !net.internal) {
                ipAddress = net.address;
                macAddress = net.mac;
                break;
            }
        }
        if (ipAddress && macAddress) break;
    }

    return { ip: ipAddress, mac: macAddress };
}

async function getUserData(token) {
    try {
        const networkInfo = await getNetworkInfo();
        console.log('>> Usuario: ' + process.env.USUARIO);
        console.log('>> IP: ' + networkInfo.ip);
        console.log('>> MAC: ' + networkInfo.mac);
        console.log('>> Hostname: ' + os.hostname());

        const headersList = {
            "Accept": "*/*",
            "Content-Type": "application/json",
            "X-Client-Mac": networkInfo.mac,
            "X-Client-Host": os.hostname(),
            "X-Client-Ip": networkInfo.ip,
            "Authorization": "Bearer " + token
        };

        const bodyContent = JSON.stringify({
            "filtrar_por": "user_ad",
            "valor": process.env.USUARIO,
        });

        const response = await axios.post(CONFIG.ENDPOINT_URL_APPS, bodyContent, {
            headers: headersList
        });
        return response.data.apps;
    } catch (error) {
        console.error('Error en la solicitud:', error);
    }
};

async function createMainWindow(appsOkan) {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 650,
        show: false,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        },
    });

    mainWindow.loadFile('./views/main/index.html');
    const webContents = mainWindow.webContents;
    webContents.setMaxListeners(50);

    webContents.on('did-stop-loading', () => {
        console.log('>> Vista main cargada');
    });

    if (process.env.MODE == 'dev') {
        mainWindow.show();
        mainWindow.openDevTools();
        // mainWindow.setKiosk(true);
    }

    mainWindow.on('ready-to-show', () => {
        mainWindow.webContents.send('set-version', app_version);
        mainWindow.webContents.send('set-userpc', process.env.USUARIO);
        try {
            mainWindow.webContents.send('data-apps', appsOkan);
        } catch (e) {
            console.log('>> Error al enviar datos:' + e);
        }

        const menuTemplate = [
            {
                label: 'Archivo',
                submenu: [
                    {
                        label: 'Recargar',
                        accelerator: 'Ctrl+Shift+R',
                        icon: __dirname + '/views/assets/icons/reload.png', // Ruta al icono
                        click: () => {
                            mainWindow.webContents.reloadIgnoringCache();
                        }
                    },
                    { type: 'separator' }, // Separador en el menú
                    {
                        label: 'Salir',
                        accelerator: 'Ctrl+Q',
                        icon: __dirname + '/views/assets/icons/exit.png', // Ruta al icono
                        click: () => {
                            app.quit();
                        }
                    }
                ]
            },
            {
                label: 'Ayuda',
                submenu: [
                    // {
                    //     label: 'Mostrar DevTools',
                    //     accelerator: 'Ctrl+Shift+L',
                    //     icon: __dirname + '/views/assets/icons/screenshot.png', // Ruta al icono
                    //     click: () => {

                    //         mainWindow.openDevTools();
                    //     }
                    // },
                    // { type: 'separator' },
                    {
                        label: 'Acerca de',
                        accelerator: 'Ctrl+Shift+A',
                        icon: __dirname + '/views/assets/icons/reload.png', // Ruta al icono
                        click: () => {
                            const { version } = require('./package.json'); // Obtener la versión desde package.json
                            dialog.showMessageBox({
                                type: 'info',
                                title: 'Acerca de Mi Aplicación',
                                message: `Versión ${version}`,
                            });
                        }
                    }
                ]
            }
        ];
        const menu = Menu.buildFromTemplate(menuTemplate);
        mainWindow.show();
        mainWindow.setMenu(menu);
        mainWindow.maximize();
    });

    mainWindow.on('closed', function () {
        mainWindow = null;
        app.quit();
    });
}

async function createNewWindow() {
    browser = await pie.connect(app, puppeteer, {
        defaultViewport: null,
        ignoreHTTPSErrors: true,
    });
    // const page = await browser.newPage();

    windowNew = new BrowserWindow({
        args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
        ignoreHTTPSErrors: true,
        width: 1200,
        height: 650,
        show: false,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            partition: 'nopersist'
        },
    });

    windowNew.setMenu(null);

    windowNew.loadURL('https://google.com');

}

const mainIni = async () => {
    await setupLogging();
    await processArguments();
    await setupProtocolClient();
    copyFilesFromRR();
    let getOkanTokenVal = await getOkanToken();
    await getProfile(getOkanTokenVal);
    userDataApps = await getUserData(getOkanTokenVal);
    console.log('>> Aplicaciones:' + userDataApps);
    appsOkan = await getApps(userDataApps);
    console.log('>> Html generado');

    await createMainWindow(appsOkan);
    await createNewWindow();
    await rpa(process.env.OKAN);
    // if(from_okan){
    //     console.log('>> Iniciando RPA desde Okan');
    //     console.log('>> Codigo:'+ process.env.OKAN);
    //     await rpa(process.env.OKAN);
    // }
};

async function rpa(data_code) {

    console.log('>> Iniciando RPA');

    if (userDataApps) {
        const codeExists = userDataApps.desk.some(app => app.code === data_code) ||
            userDataApps.web.some(app => app.code === data_code);

        if (codeExists) {
            console.log(`>> Aplicativo ${data_code} esta asociado`);
            const deskApp = userDataApps.desk.find(app => app.code === data_code);
            const webApp = userDataApps.web.find(app => app.code === data_code);

            if (deskApp) {
                type = 'desktop';
                username = deskApp.username;
                password = deskApp.password;
                xpath_username = deskApp.xpath_username;
                xpath_password = deskApp.xpath_password;
                xpath_button = deskApp.btn_login;
            } else if (webApp) {
                type = 'web';
                url_platform = webApp.url;
                username = webApp.username;
                password = webApp.password;
                xpath_username = webApp.xpath_user;
                xpath_password = webApp.xpath_pass;
                xpath_button = webApp.btn_login;

                if (!windowNew || windowNew.isDestroyed()) {
                    windowNew = new BrowserWindow({
                        args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
                        ignoreHTTPSErrors: true,
                        width: 1200,
                        height: 650,
                        show: false,
                        webPreferences: {
                            nodeIntegration: true,
                            contextIsolation: false,
                            partition: 'nopersist'
                        },
                    });
                }

                windowNew.on('closed', function () {
                    windowNew = null;
                    console.log('>> Ventana cerrada');
                });

                windowNew.loadURL(webApp.url);
                windowNew.show();
                windowNew.maximize();
                windowNew.setIgnoreMouseEvents(true);

                if (process.env.MODE != 'prod') {
                    windowNew.openDevTools();
                    windowNew.setIgnoreMouseEvents(false);
                }

                await new Promise(resolve => {
                    windowNew.webContents.on('did-finish-load', resolve);
                });

                page = await pie.getPage(browser, windowNew);
                console.log('>> URL cargada: ' + page.url());
            }

            console.log(`>> Tipo: ${type}`);
            if (type != 'desktop') {
                console.log(`>> URL: ${url_platform}`);
            }
            console.log(`>> Username: ${username}`);
            console.log(`>> Password: **********`);
            console.log('>> Xpath username: ' + xpath_username);
            console.log('>> Xpath password: ' + xpath_password);
            console.log('>> Xpath button: ' + xpath_button);

            console.log('--------------------------');
            console.log('Abriendo aplicativo');
            console.log('--------------------------');
            try {

                app.on('login', (event, webContents, request, authInfo, callback) => {
                    console.log('______________________login___________________');
                    event.preventDefault();
                    callback(username, password);
                });

                windowNew.setOpacity(1);
                windowNew.maximize();
                windowNew.setMenu(null);
                windowNew.setIgnoreMouseEvents(true);

                if (process.env.MODE != 'prod') {
                    windowNew.openDevTools();
                    windowNew.setIgnoreMouseEvents(false);
                }

                console.log('>> Url aplicativo: ' + url_platform);
                const allowedCodes = ['SMO098', 'CTD094', 'SGC095', 'MAX096', 'CUP045'];
                const specialCodes = ['MAP039'];
                const loginCodes = ['ATB089', 'VTT046', 'DSC047', 'SMO098', 'CTD094', 'SGC095', 'MAX096', 'CUP045', 'BDC087'];
                let url_mod;

                if (allowedCodes.includes(data_code)) {
                    // url_mod = `http://${username}:${password}@${data_response_service.App.replace('http://', '')}`;
                    url_mod = url_platform;
                } else {
                    url_mod = url_platform;
                }



                try {
                    if (data_code == 'POL911' || data_code == 'POL912' || data_code == 'POL913' || data_code == 'POL914' || data_code == 'POL915' || data_code == 'POD911') {
                        console.log('si poliedro');
                        url_mod = 'https://poliedro.comcel.com.co/LoginPoliedro/Login.aspx';
                    }
                    if (data_code == 'BDC087') {
                        url_mod = 'http://100.123.251.118:8082/componentes/ASP/consultabroadcast.aspx'
                    }
                    if (data_code == 'SRA074') {
                        url_mod = 'http://100.126.20.149:8080/sara/index.html'
                    }


                    await windowNew.loadURL(url_mod);
                    console.log('>> Cargo la pagina');
                } catch (error) {
                    console.log('>> No se pudo cargar la pagina: ' + error);
                    dialog.showErrorBox('Error', 'No se pudo cargar la pagina. Por favor reporta al Helpdesk');
                    windowNew.setOpacity(1);
                    windowNew.close();
                }


                // const page = await pie.getPage(browser, windowNew);
                try {
                    // const pages = await browser.pages().then(pages => pages).catch(err => console.error(err));
                    // console.log(pages);
                    // var page;
                    var pageUrl;

                    // for (const pages_sel of pages) {
                    //     const pageUrl = await pages_sel.url();
                    //     // console.log('la obtenida: ' + pageUrl + '_____' + 'la real: ' + url_mod);
                    //     if (pageUrl == 'http://100.126.20.149:8080/sara/login') {
                    //         url_mod = 'http://100.126.20.149:8080/sara/login';
                    //     }
                    //     if (pageUrl == 'http://dime.claro.com.co/Portal/Produccion/Sesion/Inicio/Ingresar?ReturnUrl=%2FPortal%2FProduccion%2FFidelizacion%2FRetencion%2FRegistrarSolicitud%3Fdato%3D1007227477%26Cuenta%3D89715445%26Ticket%3D1%26Internet%3D1%26TV%3D1%26Telefonia%3D0') {
                    //         url_mod = 'http://dime.claro.com.co/Portal/Produccion/Sesion/Inicio/Ingresar?ReturnUrl=%2FPortal%2FProduccion%2FFidelizacion%2FRetencion%2FRegistrarSolicitud%3Fdato%3D1007227477%26Cuenta%3D89715445%26Ticket%3D1%26Internet%3D1%26TV%3D1%26Telefonia%3D0';
                    //     }
                    //     if (pageUrl === url_mod) {
                    //         console.log(`Ok pagina`);
                    //         page = pages_sel;
                    //         break; // Detén el bucle cuando encuentras la coincidencia
                    //     }
                    // }

                    if (page) {
                        console.log(`Nombre de la pagina: ${await page.title()}`);
                        // await page.waitForLoad();
                        if (xpath_username != 'na') {
                            if (data_code == 'POL911' || data_code == 'POL912' || data_code == 'POL913' || data_code == 'POL914' || data_code == 'POL915' || data_code == 'POD911') {
                                await page.waitForXPath('//input[@id="ctl00_ContentPlaceHolder1_BtnRegresarMensaje"]');
                                const backBtn = await page.$x('//input[@id="ctl00_ContentPlaceHolder1_BtnRegresarMensaje"]');
                                await backBtn[0].click();
                            }
                            if (!loginCodes.includes(data_code)) {

                                if (data_code == 'CLU100') {
                                    const elementHandleClu = await page.$('.sign-in-uclaro');
                                    if (elementHandleClu) {
                                        await elementHandleClu.click();
                                    }
                                }

                                await page.waitForXPath(xpath_username);
                                const elementHandleUser = await page.$x(xpath_username);
                                await elementHandleUser[0].type('', { delay: 100 });
                                await elementHandleUser[0].type(username);
                                console.log('>> Diligencio campo usuario');

                                if (data_code == 'ABS099') {
                                    await page.keyboard.press("Enter");
                                } else {
                                    await page.keyboard.press("Tab");
                                }

                                if (data_code == 'AGE036') {
                                    await page.waitForTimeout(4000);
                                } else {
                                    await page.waitForTimeout(1000);
                                }

                                await page.waitForXPath(xpath_password);
                                const elementHandlePass = await page.$x(xpath_password);
                                await elementHandlePass[0].type('', { delay: 100 });
                                await elementHandlePass[0].type(password);
                                console.log('>> Diligencio campo password');

                                await page.waitForTimeout(1000);
                                const xpathMap = {
                                    'DIM072': '//button[contains(@id, "btiniciar")]',
                                    'CLU100': '//button[contains(@class, "ingresarBoton")]',
                                    'MAP039': xpath_button,
                                    'CMC093': xpath_button,
                                    'MCA030': '//input[contains(@id, "login-button")]'
                                };

                                const xpath = xpathMap[data_code] || null;

                                if (xpath) {
                                    const elementHandle = await page.$x(xpath);
                                    if (elementHandle && elementHandle.length > 0) {
                                        await elementHandle[0].click();
                                        console.log('>> Se dio click en boton');
                                    } else {
                                        console.log('>> No encontro boton');
                                    }
                                } else {
                                    await page.keyboard.press('Enter');
                                }
                            }

                            // await page.waitForTimeout(70000);


                            console.log('>> Envio formulario');

                            await page.waitForTimeout(7000);

                            if (data_code == 'POL911' || data_code == 'POL912' || data_code == 'POL913' || data_code == 'POL914' || data_code == 'POL915' || data_code == 'POD911') {
                                elementToken = await page.$x(`//*[contains(text(), "un nuevo token a su dispositivo")]`, { timeout: 1000 });
                                if (elementToken) {
                                    console.log('>> No se encontro mensaje de error de credenciales:');
                                } else {
                                    console.log('>> Se encontro mensaje de error de credenciales:');
                                    dialog.showErrorBox('Error', 'Parece que hubo un problema con el ingreso. Por favor, repórtalo al Coordinador');
                                    windowNew.close();
                                }
                            } else {
                                const checkAndClose = async (message, text, xpath) => {
                                    var elementHandles;
                                    if (xpath) {
                                        elementHandles = await page.$x(text, { timeout: 1000 });
                                    } else {
                                        if (data_code != 'SRA074' && text != 'valid') {
                                            elementHandles = await page.$x(`//*[contains(text(), "${text}")]`, { timeout: 1000 });
                                        }
                                    }


                                    if (elementHandles && elementHandles.length > 0) {
                                        if (data_code == 'VIM059' && elementHandles.length <= 2) {

                                        } else if (data_code == 'DIM072' && elementHandles.length <= 1) {

                                        }
                                        else {
                                            console.log('Se encontro mensaje de error de credenciales: ${message}');
                                            dialog.showErrorBox('Error', 'Parece que hubo un problema con el ingreso. Por favor, repórtalo al Coordinador');
                                            windowNew.close();
                                        }
                                    } else {
                                        console.log('>> No se encontro mensaje de error de credenciales: ${message}');
                                    }
                                };

                                await checkAndClose('Incorrect', 'incorrect', false) ||
                                    await checkAndClose('Incorrectos', 'INCORRECTOS', false) ||
                                    await checkAndClose('Error', 'error', false) ||
                                    await checkAndClose('Error', 'Error', false) ||
                                    await checkAndClose('Errada', 'errad', false) ||
                                    await checkAndClose('Valid', 'valid', false) ||
                                    await checkAndClose('Could not log', 'could not log', false) ||
                                    await checkAndClose('Form', xpath_username, true);

                            }
                        }
                        windowNew.setIgnoreMouseEvents(false);
                        // windowNew.setOpacity(1);
                        // windowNew.maximize();
                        // windowNew.focus();
                    } else {
                        console.log('>> No se encontro ninguna pagina con la URL proporcionada.');
                    }


                } catch (error) {
                    console.log(error);
                }

            } catch (error) {
                windowNew.setOpacity(1);
                windowNew.close();
                console.error('Ha ocurrido un error ', data_code, error);
                dialog.showErrorBox('Error', 'Ha ocurrido un error ' + error);
            }


        } else {
            console.log(`>> Aplicativo ${data_code} no esta asociado`);
            await dialog.showMessageBox({
                type: 'error',
                defaultId: 0,
                title: 'Error de acceso',
                message: 'Lo siento, no tienes acceso a este aplicativo',
            });
        }
    }













    // let programa = '';
    // switch (data_code) {
    //     case 'IRR123':
    //         console.log('IRR123');

    //         rrtest = rr(username, password);
    //         console.log(rrtest);

    //         break;
    //     case 'ACC098':
    //         console.log('ACC098');

    //         programa = '"C:\\Program Files (x86)\\AC Administración de Clientes\\AC Administrador de Clientes.exe"';
    //         exec(programa, (error, stdout, stderr) => {
    //             if (error) {
    //                 console.error(`Error al abrir el programa: ${error.message}`);
    //                 return;
    //             }
    //             if (stderr) {
    //                 console.error(`Error en la salida estándar: ${stderr}`);
    //                 return;
    //             }
    //             console.log(`Salida del programa: ${stdout}`);
    //         });

    //         break;

    //     case 'AVY003':
    //         console.log('AVY003');

    //         programa = '"C:\\Program Files (x86)\\Avaya\\Avaya one-X Agent\\OneXAgentUI.exe"';
    //         exec(programa, (error, stdout, stderr) => {
    //             if (error) {
    //                 console.error(`Error al abrir el programa: ${error.message}`);
    //                 return;
    //             }
    //             if (stderr) {
    //                 console.error(`Error en la salida estándar: ${stderr}`);
    //                 return;
    //             }
    //             console.log(`Salida del programa: ${stdout}`);
    //         });

    //         break;

    //     case 'XLT001':
    //         console.log('XLT001');

    //         programa = '"C:\\Program Files (x86)\\CounterPath\\X-Lite\\x-lite.exe"';
    //         exec(programa, (error, stdout, stderr) => {
    //             if (error) {
    //                 console.error(`Error al abrir el programa: ${error.message}`);
    //                 return;
    //             }
    //             if (stderr) {
    //                 console.error(`Error en la salida estándar: ${stderr}`);
    //                 return;
    //             }
    //             console.log(`Salida del programa: ${stdout}`);
    //         });

    //         break;

    //     case 'CTB002':
    //         console.log('CTB002');

    //         programa = '"C:\\avaya\\CTIbar\\ctibar.exe"';
    //         exec(programa, (error, stdout, stderr) => {
    //             if (error) {
    //                 console.error(`Error al abrir el programa: ${error.message}`);
    //                 return;
    //             }
    //             if (stderr) {
    //                 console.error(`Error en la salida estándar: ${stderr}`);
    //                 return;
    //             }
    //             console.log(`Salida del programa: ${stdout}`);
    //         });

    //         break;



    //     default:
    //         const browser = await pie.connect(app, puppeteer, {
    //             defaultViewport: null,
    //             ignoreHTTPSErrors: true,
    //         });

    //         const pages = await browser.pages().then(pages => pages).catch(err => console.error(err));


    //         if (data_apps) {
    //             const windowNew = new BrowserWindow({
    //                 args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
    //                 ignoreHTTPSErrors: true,
    //                 webPreferences: {
    //                     partition: 'nopersist'
    //                 }
    //             });


    //             const page = await pie.getPage(browser, windowNew);
    //             console.log('page');
    //             console.log(page.url());

    //             // windowNew.webContents.session.setCacheEnabled(false);
    //             windowNew.webContents.session.clearStorageData();
    //             // windowNew.webContents.session.setStorageEnabled(false)
    //             windowNew.webContents.session.clearCache();

    //             console.log('--------------------------');
    //             console.log('Abriendo aplicativo');
    //             console.log('--------------------------');
    //             try {

    //                 app.on('login', (event, webContents, request, authInfo, callback) => {
    //                     console.log('______________________login___________________');
    //                     event.preventDefault();
    //                     callback(username, password);
    //                 });

    //                 windowNew.setOpacity(1);
    //                 windowNew.maximize();
    //                 windowNew.setMenu(null);
    //                 windowNew.setIgnoreMouseEvents(true);

    //                 if (process.env.MODE != 'prod') {
    //                     windowNew.openDevTools();
    //                     windowNew.setIgnoreMouseEvents(false);
    //                 }

    //                 console.log('>> Url aplicativo: ' + url_platform);
    //                 const allowedCodes = ['SMO098', 'CTD094', 'SGC095', 'MAX096', 'CUP045'];
    //                 const specialCodes = ['MAP039'];
    //                 const loginCodes = ['ATB089', 'VTT046', 'DSC047', 'SMO098', 'CTD094', 'SGC095', 'MAX096', 'CUP045', 'BDC087'];
    //                 let url_mod;

    //                 if (allowedCodes.includes(data_code)) {
    //                     // url_mod = `http://${username}:${password}@${data_response_service.App.replace('http://', '')}`;
    //                     url_mod = url_platform;
    //                 } else {
    //                     url_mod = url_platform;
    //                 }



    //                 try {
    //                     if (data_code == 'POL911' || data_code == 'POL912' || data_code == 'POL913' || data_code == 'POL914' || data_code == 'POL915' || data_code == 'POD911') {
    //                         console.log('si poliedro');
    //                         url_mod = 'https://poliedro.comcel.com.co/LoginPoliedro/Login.aspx';
    //                     }
    //                     if (data_code == 'BDC087') {
    //                         url_mod = 'http://100.123.251.118:8082/componentes/ASP/consultabroadcast.aspx'
    //                     }
    //                     if (data_code == 'SRA074') {
    //                         url_mod = 'http://100.126.20.149:8080/sara/index.html'
    //                     }


    //                     // console.log('url_mod: '+url_mod);

    //                     // const encodedUrl = querystring.escape(url_mod);
    //                     // console.log('codificada: '+encodedUrl);
    //                     await windowNew.loadURL(url_mod);
    //                     console.log('>> Cargo la pagina');
    //                 } catch (error) {
    //                     console.log('>> No se pudo cargar la pagina: ' + error);
    //                     dialog.showErrorBox('Error', 'No se pudo cargar la pagina. Por favor reporta al Helpdesk');
    //                     windowNew.setOpacity(1);
    //                     windowNew.close();
    //                 }


    //                 // const page = await pie.getPage(browser, windowNew);
    //                 try {
    //                     // const pages = await browser.pages().then(pages => pages).catch(err => console.error(err));
    //                     // console.log(pages);
    //                     // var page;
    //                     var pageUrl;

    //                     for (const pages_sel of pages) {
    //                         const pageUrl = await pages_sel.url();
    //                         // console.log('la obtenida: ' + pageUrl + '_____' + 'la real: ' + url_mod);
    //                         if (pageUrl == 'http://100.126.20.149:8080/sara/login') {
    //                             url_mod = 'http://100.126.20.149:8080/sara/login';
    //                         }
    //                         if (pageUrl == 'http://dime.claro.com.co/Portal/Produccion/Sesion/Inicio/Ingresar?ReturnUrl=%2FPortal%2FProduccion%2FFidelizacion%2FRetencion%2FRegistrarSolicitud%3Fdato%3D1007227477%26Cuenta%3D89715445%26Ticket%3D1%26Internet%3D1%26TV%3D1%26Telefonia%3D0') {
    //                             url_mod = 'http://dime.claro.com.co/Portal/Produccion/Sesion/Inicio/Ingresar?ReturnUrl=%2FPortal%2FProduccion%2FFidelizacion%2FRetencion%2FRegistrarSolicitud%3Fdato%3D1007227477%26Cuenta%3D89715445%26Ticket%3D1%26Internet%3D1%26TV%3D1%26Telefonia%3D0';
    //                         }
    //                         if (pageUrl === url_mod) {
    //                             console.log(`Ok pagina`);
    //                             page = pages_sel;
    //                             break; // Detén el bucle cuando encuentras la coincidencia
    //                         }
    //                     }

    //                     if (page) {
    //                         console.log(`Nombre de la pagina: ${await page.title()}`);
    //                         // await page.waitForLoad();
    //                         if (xpath_username != 'na') {
    //                             if (data_code == 'POL911' || data_code == 'POL912' || data_code == 'POL913' || data_code == 'POL914' || data_code == 'POL915' || data_code == 'POD911') {
    //                                 await page.waitForXPath('//input[@id="ctl00_ContentPlaceHolder1_BtnRegresarMensaje"]');
    //                                 const backBtn = await page.$x('//input[@id="ctl00_ContentPlaceHolder1_BtnRegresarMensaje"]');
    //                                 await backBtn[0].click();
    //                             }
    //                             if (!loginCodes.includes(data_code)) {

    //                                 if (data_code == 'CLU100') {
    //                                     const elementHandleClu = await page.$('.sign-in-uclaro');
    //                                     if (elementHandleClu) {
    //                                         await elementHandleClu.click();
    //                                     }
    //                                 }

    //                                 await page.waitForXPath(xpath_username);
    //                                 const elementHandleUser = await page.$x(xpath_username);
    //                                 await elementHandleUser[0].type('', { delay: 100 });
    //                                 await elementHandleUser[0].type(username);
    //                                 console.log('>> Diligencio campo usuario');

    //                                 if (data_code == 'ABS099') {
    //                                     await page.keyboard.press("Enter");
    //                                 } else {
    //                                     await page.keyboard.press("Tab");
    //                                 }

    //                                 if (data_code == 'AGE036') {
    //                                     await page.waitForTimeout(4000);
    //                                 } else {
    //                                     await page.waitForTimeout(1000);
    //                                 }

    //                                 await page.waitForXPath(xpath_password);
    //                                 const elementHandlePass = await page.$x(xpath_password);
    //                                 await elementHandlePass[0].type('', { delay: 100 });
    //                                 await elementHandlePass[0].type(password);
    //                                 console.log('>> Diligencio campo password');

    //                                 await page.waitForTimeout(1000);
    //                                 const xpathMap = {
    //                                     'DIM072': '//button[contains(@id, "btiniciar")]',
    //                                     'CLU100': '//button[contains(@class, "ingresarBoton")]',
    //                                     'MAP039': xpath_button,
    //                                     'CMC093': xpath_button,
    //                                     'MCA030': '//input[contains(@id, "login-button")]'
    //                                 };

    //                                 const xpath = xpathMap[data_code] || null;

    //                                 if (xpath) {
    //                                     const elementHandle = await page.$x(xpath);
    //                                     if (elementHandle && elementHandle.length > 0) {
    //                                         await elementHandle[0].click();
    //                                         console.log('>> Se dio click en boton');
    //                                     } else {
    //                                         console.log('>> No encontro boton');
    //                                     }
    //                                 } else {
    //                                     await page.keyboard.press('Enter');
    //                                 }
    //                             }

    //                             // await page.waitForTimeout(70000);


    //                             console.log('>> Envio formulario');

    //                             await page.waitForTimeout(7000);

    //                             if (data_code == 'POL911' || data_code == 'POL912' || data_code == 'POL913' || data_code == 'POL914' || data_code == 'POL915' || data_code == 'POD911') {
    //                                 elementToken = await page.$x(`//*[contains(text(), "un nuevo token a su dispositivo")]`, { timeout: 1000 });
    //                                 if (elementToken) {
    //                                     console.log('>> No se encontro mensaje de error de credenciales:');
    //                                 } else {
    //                                     console.log('>> Se encontro mensaje de error de credenciales:');
    //                                     dialog.showErrorBox('Error', 'Parece que hubo un problema con el ingreso. Por favor, repórtalo al Coordinador');
    //                                     windowNew.close();
    //                                 }
    //                             } else {
    //                                 const checkAndClose = async (message, text, xpath) => {
    //                                     var elementHandles;
    //                                     if (xpath) {
    //                                         elementHandles = await page.$x(text, { timeout: 1000 });
    //                                     } else {
    //                                         if (data_code != 'SRA074' && text != 'valid') {
    //                                             elementHandles = await page.$x(`//*[contains(text(), "${text}")]`, { timeout: 1000 });
    //                                         }
    //                                     }


    //                                     if (elementHandles && elementHandles.length > 0) {
    //                                         if (data_code == 'VIM059' && elementHandles.length <= 2) {

    //                                         } else if (data_code == 'DIM072' && elementHandles.length <= 1) {

    //                                         }
    //                                         else {
    //                                             console.log('Se encontro mensaje de error de credenciales: ${message}');
    //                                             dialog.showErrorBox('Error', 'Parece que hubo un problema con el ingreso. Por favor, repórtalo al Coordinador');
    //                                             windowNew.close();
    //                                         }
    //                                     } else {
    //                                         console.log('>> No se encontro mensaje de error de credenciales: ${message}');
    //                                     }
    //                                 };

    //                                 await checkAndClose('Incorrect', 'incorrect', false) ||
    //                                     await checkAndClose('Incorrectos', 'INCORRECTOS', false) ||
    //                                     await checkAndClose('Error', 'error', false) ||
    //                                     await checkAndClose('Error', 'Error', false) ||
    //                                     await checkAndClose('Errada', 'errad', false) ||
    //                                     await checkAndClose('Valid', 'valid', false) ||
    //                                     await checkAndClose('Could not log', 'could not log', false) ||
    //                                     await checkAndClose('Form', xpath_username, true);

    //                             }
    //                         }
    //                         windowNew.setIgnoreMouseEvents(false);
    //                         // windowNew.setOpacity(1);
    //                         // windowNew.maximize();
    //                         // windowNew.focus();
    //                     } else {
    //                         console.log('>> No se encontro ninguna pagina con la URL proporcionada.');
    //                     }


    //                 } catch (error) {
    //                     console.log(error);
    //                 }

    //             } catch (error) {
    //                 windowNew.setOpacity(1);
    //                 windowNew.close();
    //                 console.error('Ha ocurrido un error ', data_code, error);
    //                 dialog.showErrorBox('Error', 'Ha ocurrido un error ' + error);
    //             }
    //         }

    //         break;
    // }



};

// Ensure mainIni is called after app is ready
app.on('ready', mainIni);

const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
    app.quit();
} else {
    app.on('second-instance', async (event, argv, workingDirectory) => {
        console.log('>> Segunda instancia');
        console.log(argv);
        // Focus the main window if a second instance is detected
        if (mainWindow) {
            if (mainWindow.isMinimized()) mainWindow.restore();
            mainWindow.focus();
        }

        process.env.MODE = 'prod';
        let url_okan = argv[3];
        let code_okan_str = url_okan.toString();
    
        // Handle OKAN code from URL or direct argument
        if (argv[3] && !argv.dev) {
    
            let code_okan = code_okan_str.split('&')[0].replace('rpaclaro:///?code=', '');
            let user_okan = code_okan_str.split('&')[1].replace('user=', '');
            process.env.OKAN = code_okan;
            process.env.USUARIO = user_okan;
            console.log('>> Sgundos instancia code: '+process.env.OKAN);
            await rpa(process.env.OKAN);
        } else {
            process.env.OKAN = argv.code;
            process.env.USUARIO = argv.user;
        }
    
        // Set environment mode
        if (argv.dev) {
            process.env.MODE = 'dev';
        } else {
            process.env.MODE = 'prod';
        }
    
        console.log('>> Iniciando RpaClaro..');
        console.log('_____________________________');
        console.log('RPA CLARO');
        console.log('Usuario: ' + process.env.USUARIO);
        console.log('Version: ' + app_version);
        console.log('Modo: ' + process.env.MODE);
        console.log('_____________________________');

    });

    // app.on('ready', mainIni);
}

// ... existing code ...

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

app.commandLine.appendSwitch('ignore-certificate-errors');

app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
    event.preventDefault();
    callback(true);
});

ipcMain.on('openNewWindow', (event, data_code) => {
    rpa(data_code);
});

ipcMain.on('newNotification', (event, message) => {
    const notification = new Notification({
        title: message.title,
        body: message.body,
        icon: 'logo-claro.ico'
    });
    notification.show();
});

ipcMain.on('show-help', () => {
    dialog.showMessageBox({
        type: 'info',
        title: 'Acerca de Mi Aplicación',
        message: `Versión `+app.getVersion(),
    });
});

ipcMain.on('reload-app', () => {
    mainWindow.webContents.reloadIgnoringCache(); // Reload main window ignoring cache
});

ipcMain.on('close-app', () => {
    app.quit(); // Cierra la aplicación
});
