const sdk = require('matrix-js-sdk');
const fs = require('fs');
// const { ipcRenderer } = require('electron');

function saveScreenshot(dataUrl) {
    // Obtener el contenido base64 de la imagen
    const base64Data = dataUrl.replace(/^data:image\/png;base64,/, '');

    // Especificar la ruta donde se guardará la captura de pantalla
    const filePath = 'screenshot.png';

    // Escribir la imagen en el disco
    fs.writeFile(filePath, base64Data, 'base64', (error) => {
        if (error) {
            console.error('Error saving screenshot:', error);
        } else {
            console.log('Screenshot saved successfully:', filePath);
        }
    });
}

$('#helpdesk').on('submit', function (event) {
    event.preventDefault();
    $('#loader').css('display', 'flex');
    var description = $('#description').val();

    try {

        const client = sdk.createClient({
            baseUrl: "https://matrixadm.mind.brm.co",
            accessToken: "syt_YnJhamFuLmFsZGFuYQ_GsGDJXWtpWkuTayxUIff_4OAXsg",
            userId: "@brajan.aldana:matrixadm.mind.brm.co"
        });

        client.on("sync", (state, prevState, res) => {
            if (state === "SYNCING" && prevState === "SYNCING") {
                // La sincronización está en progreso
            } else if (state === "SYNCING" && prevState !== "SYNCING") {
                // La sincronización acaba de comenzar
            } else if (state === "PREPARED" && prevState === "SYNCING") {
                // La sincronización ha terminado, ahora puedes detener el cliente
                client.stopClient();
            }
        });

        var roomid = "!EKItKhtVBxGSvkbPtx:matrixadm.mind.brm.co";

        client.startClient();

        const info_msg = {
            "body": "Status: **success**<br/> Build: by xoxys",
            "msgtype": "m.notice",
            "format": "org.matrix.custom.html",
            "formatted_body": "<h4>Solicitud HelpDesk</h4><p>Usuario: <strong>EC9596Q</strong><br/>Cedula: <strong>1022969596</strong><br/>" + description + "</p>\n",
        };

        client.sendMessage(roomid, info_msg);




        setTimeout(() => {

            const filename = "C:/RpaClaro/video.webm";

            const contentBuffer = fs.readFileSync(filename);
            const blob = new Blob([contentBuffer], { type: "video/webm" });

            client.uploadContent(blob, {
                name: "video.webm",
                type: "video/webm"
            }).then(function (url) {
                var content = {
                    msgtype: "m.video",
                    body: filename,
                    info: {
                        mimetype: "video/webm"
                    },
                    url: url.content_uri
                };
                client.sendMessage(roomid, content);
            });
            console.log('envio video');

        }, 2000);

        setTimeout(() => {

            const filename = "C:/RpaClaro/logs.txt";

            const contentBuffer = fs.readFileSync(filename);
            const blob = new Blob([contentBuffer], { type: "text/plain" });

            client.uploadContent(blob, {
                name: "logs.txt",
                type: "text/plain"
            }).then(function (url) {
                var content = {
                    msgtype: "m.file",
                    body: filename,
                    info: {
                        mimetype: "text/plain"
                    },
                    url: url.content_uri
                };
                client.sendMessage(roomid, content);
            });

            setTimeout(() => {
                client.stopClient();
                console.log('termino');

            }, 5000);
            console.log('envio txt');

        }, 2000);


        setTimeout(() => {
            client.stopClient();
            console.log('termino');
            $('#loader').css('display', 'none');
            $('#description').val('');
            $('#close_drawer').trigger('click');
            $('#description').attr('disabled', 'disabled');
            $('#send').attr('disabled', 'disabled');
            $('#record').css('display', 'block');
        }, 5000);
    } catch (e) {
        console.error('Problema al enviar info Element', e);
    }
});


$('#screenshot').on('click', function (event) {
    console.log('screenshot');
    ipcRenderer.send('screenshot');
    ipcRenderer.once('screenshot-response', (event, response) => {
        console.log('Respuesta del proceso principal:', response);
    });

});



function handleStream(stream) {
    const video = document.querySelector('video')
    video.srcObject = stream
    video.onloadedmetadata = (e) => video.play()
}

function handleError(e) {
    console.log(e)
}

$('#record').on('click', function (event) {
    console.log('record');
    $('#record').css('display', 'none');
    $('#close_drawer').trigger('click');
    ipcRenderer.send('newNotification', { 'title': 'Recopilando evidencias', 'body': 'Grabando pantalla...' });
    ipcRenderer.send('newLog', {window:'main', log: '-----------------------', msg: '-----------------------', splash: false});
    ipcRenderer.send('newLog', {window:'main', log: 'SOLICITUD HELPDESK', msg: 'SOLICITUD HELPDESK', splash: false});
    ipcRenderer.send('newLog', {window:'main', log: '-----------------------', msg: '-----------------------', splash: false});
    ipcRenderer.send('newLog', {window:'main', log: 'Recopilando evidencias', msg: 'Recopilando evidencias', splash: false});
    ipcRenderer.send('record');
    ipcRenderer.once('record-response', async (event, response) => {
        console.log('devolvio ventana');
        ipcRenderer.send('newLog', {window:'main', log: 'Respuesta del proceso principal: '+ response, 'msg': 'Respuesta del proceso principal', splash: false});
        setTimeout(async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({
                    audio: false,
                    video: {
                        mandatory: {
                            chromeMediaSource: 'desktop',
                            chromeMediaSourceId: response,
                            minWidth: 1280,
                            maxWidth: 1280,
                            minHeight: 720,
                            maxHeight: 720,
                        },
                    },
                });

                const mediaRecorder = new MediaRecorder(stream);
                const chunks = [];

                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        chunks.push(event.data);
                    }
                };

                mediaRecorder.onstop = () => {
                    const blob = new Blob(chunks, { type: 'video/webm' });
                    blob.arrayBuffer().then((buffer) => {
                        ipcRenderer.send('save-video', buffer);
                        ipcRenderer.send('newLog', {window:'main', log:'Termino recopilacion', msg: 'Termino recopilacion', splash: false});

                        $('#open_drawer').text('Solicitar HelpDesk');
                        $('#open_drawer').trigger('click');
                        $('#description').removeAttr('disabled');
                        $('#send').removeAttr('disabled');
                    });
                };

                mediaRecorder.start();

                // Después de un tiempo (por ejemplo, 5000 ms), detener la grabación
                setTimeout(async () => {
                    mediaRecorder.stop();
                    stream.getTracks().forEach((track) => track.stop());
                }, 22000);
            } catch (e) {
                console.error('Error:', e);
            }
        }, 2000);
    });

    ipcRenderer.once('send-video', async (event, response) => {
        ipcRenderer.send('newLog', {window:'splash', log:'Enviando video', msg: 'Enviando video', splash: true});

        const client = sdk.createClient({
            baseUrl: "https://matrixadm.mind.brm.co",
            accessToken: "syt_YnJhamFuLmFsZGFuYQ_GsGDJXWtpWkuTayxUIff_4OAXsg",
            userId: "@brajan.aldana:matrixadm.mind.brm.co"
        });

        client.startClient();

        client.once('sync', function (state, prevState, res) {
            console.log(state);
        });

        var roomid = "!EKItKhtVBxGSvkbPtx:matrixadm.mind.brm.co";

        const filename = "C:/Users/LENOVO/Desktop/REPOS/rpa-claro/video.webm";

        const contentBuffer = fs.readFileSync(filename);
        const blob = new Blob([contentBuffer], { type: "video/webm" });

        client.uploadContent(blob, {
            name: "video.webm",
            type: "video/webm"
        }).then(function (url) {
            var content = {
                msgtype: "m.video",
                body: filename,
                info: {
                    mimetype: "video/webm"
                },
                url: url.content_uri
            };
            client.sendMessage(roomid, content);
        });

        setTimeout(() => {
            client.stopClient();
            console.log('termino');
        }, 2000);
        ipcRenderer.send('newLog', { 'log': 'Envio video', 'msg': '' });
    });

});