const $ = require('jquery');
const axios = require('axios');
const os = require('os');

let data_apps_user = []; // Initialize as an empty array

ipcRenderer.on('data-apps', (event, data_apps) => {
    data_apps_user = data_apps;
});

$('#loader').css('display', 'flex');
async function index() {
    try {
        const urlOkan = "https://io.okan.tools/api/auth/electron";
        const token = 'HrZTvmBNyQaM6jPI7sHo5ywN35ht/cplIBFeE+4Ufx8=';
        const urlGetProfile = 'https://io.okan.tools/api/auth/users/electron';
        let documento;
        let profile;
        try {
            const responseOkan = await axios.post(urlOkan, { user: process.env.USUARIO }, { headers: { 'Authorization': token } });
            if (responseOkan.data.cod == '0') {
                const token_okan = 'Bearer ' + responseOkan.data.data;
                try {
                    const responseGetProfile = await axios.get(urlGetProfile, { headers: { 'Authorization': token_okan } });
                    if (responseGetProfile.data.cod == '0') {
                        documento = responseGetProfile.data.data.document_number;
                        profile = responseGetProfile.data.data.profile.id;
                    } else {
                        ipcRenderer.send('newLog', { window: 'splash', log: 'Ha ocurrido un error: ' + responseGetProfile.data.message, msg: 'Ha ocurrido un error', splash: true });
                    }
                } catch (e) {
                    ipcRenderer.send('newLog', { window: 'splash', log: 'Error al obtener el perfil: ' + e, msg: 'Error al obtener el perfil: ' + e, splash: true });
                }
            } else {
                ipcRenderer.send('newLog', { window: 'splash', log: 'Ha ocurrido un error: ' + responseGetProfile.data.message, msg: 'Ha ocurrido un error', splash: true });
            }
        } catch (error) {
            ipcRenderer.send('newLog', { window: 'splash', log: 'Error al obtener el token: ' + error, msg: 'Error al obtener el token: ' + error, splash: true });
        }




        const urlAplicativos = `https://adm.okan.tools/wp-json/okanapiwp/v1/aplicativos/${documento}/${profile}`;
        const responseAplicativos = await axios.get(urlAplicativos, { headers: { "Accept": "*/*", "Content-Type": "application/json" } });

        var apps_okan = [];
        var type_app;
        var url_service;
        var code_app;
        let new_apps = [];
        if (responseAplicativos.data['cod'] == '0') {
            console.log('_________________');
            console.log('Aplicativos:');
            console.log(responseAplicativos.data['data']);
            console.log('_________________');

            console.log('data_apps:', data_apps_user);

            // Filter RPA apps and extract codes in one pass
            const new_apps = responseAplicativos.data['data'].filter(element =>
                element['url'].includes('RpaClaro://?code=')
            );

            console.log(new_apps);

        // Process each app from new_apps
        for (const app of new_apps) {
            // Check if app code exists in data_apps_user
            const appExists = data_apps_user.web?.some(webApp => webApp.code === app.url.split('=')[1]) || 
                            data_apps_user.desk?.some(deskApp => deskApp.code === app.url.split('=')[1]);

            // Extract app information
            const appInfo = {
                nombre_app: app.nombre_app,
                // type_app: app.tipo,
                code_app: app.url.split('=')[1],
                logo: app.logo,
                status: appExists,
                status_integrado: appExists ? 'integrado' : 'no_integrado',
            };

            // Add to apps_okan array
            apps_okan.push(appInfo);

            // Add HTML element for the app
            $('#aplicativos').append(`
                <div class="col-3 col-md-3 col-xl-3 shortcut app_click ${appInfo.status_integrado}" 
                    name_app="${appInfo.nombre_app}" 
                    integrado="${appInfo.status}" 
                    code="${appInfo.code_app}">
                    <div class="card border-none text-center">
                        <div class="card-body hp-knowledge-basic-card">
                            <img src="${appInfo.logo}" class="logo">
                            <h5>${appInfo.nombre_app}</h5>
                        </div>
                    </div>
                </div>
            `);
        }

        console.log(apps_okan);






        }



        async function processApps() {
            for (const element of apps_okan) {
                await new Promise(resolve => setTimeout(resolve, 100));
                // await makeRequest(element);
            }

            // Lógica de ordenación
            var divs = $('.shortcut').sort(function (a, b) {
                var textoA = $(a).find('h5').text().toUpperCase();
                var textoB = $(b).find('h5').text().toUpperCase();
                return (textoA < textoB) ? -1 : (textoA > textoB) ? 1 : 0;
            });

            // Limpia el contenedor original
            $('.shortcut').remove();

            // Agrega los divs ordenados de nuevo al contenedor
            divs.appendTo('#aplicativos');

            ipcRenderer.send('newLog', { window: 'splash', log: 'Termino de ordenar', msg: 'Estamos terminando...', splash: true });

            // Esperar un poco antes de emitir el evento 'ordeno'
            setTimeout(function () {
                console.log('ordeno apps');
                ipcRenderer.send('ordeno');
                $('#loader').css('display', 'none');
            }, 2000);
        }

        processApps();
    } catch (error) {
        console.log("Error en la ejecución: " + error);
        ipcRenderer.send('newLog', { window: 'splash', log: 'Error en la ejecución', msg: 'Ha ocurrido un error: ' + error, splash: true });
    }
}
index();

$(document).on("click", ".app_click", function () {
    ipcRenderer.send('newNotification', { 'title': 'Abriendo aplicativo', 'body': $(this).attr('name_app') });
    console.log('click');
    console.log($(this).attr('integrado'));
    if ($(this).attr('integrado') == 'true') {
        data_code = $(this).attr('code')
        console.log(data_code);
        ipcRenderer.send('openNewWindow', data_code);
    } else {
        error_window = {
            title: 'Error de aplicativo',
            content: 'No tienes habilitado este aplicativo, informa al coordinador'
        }
        ipcRenderer.send('error_window', error_window);
    }
});

$('#search-input').on('input', function () {
    var textoBusqueda = $(this).val().toUpperCase();
    $('.shortcut').each(function () {
        var textoElemento = $(this).find('h5').text().toUpperCase();
        var elemento = $(this);
        elemento.toggle(textoElemento.includes(textoBusqueda));
    });
});

$('#active_apps').on('click', function () {
    var elementosFiltrados = $('.shortcut[integrado="true"]');
    $('.shortcut').hide();
    elementosFiltrados.show();
});

$('#inactive_apps').on('click', function () {
    var elementosFiltrados = $('.shortcut[integrado="false"]');
    $('.shortcut').hide();
    elementosFiltrados.show();
});

$('#all_apps').on('click', function () {
    $('.shortcut').show();
});
