//Fran Macías 2025 (& Adri & Guille)
// Xerador Créditos v2.3
// CC BY SA 4.0
var fileInputhtml, fileInputcsv, btgardacode, btconf, contConf, docurl, btlimp, btabrir, axuda, abriraxuda, pecharaxuda, btselconf, btcopia, btprocesa, btexpcsv, btimpcsv, btrexe;
var datosPaxinas = [];
document.addEventListener("DOMContentLoaded", (event) => {
    document.querySelector('.textcode').value = '';
    fileInputhtml = document.querySelector('.selector > #cargaFicheiroshtml');
    fileInputcsv = document.querySelector('.selector > #cargaFicheiroscsv');
    btgardacode = document.querySelector('.code');
    btconf = document.querySelector('.config');
    contConf = document.querySelector('.templ');
    btlimp = document.querySelector('.borra');
    btabrir = document.querySelector('.abre');
    btselconf = document.querySelector('.selconf');
    btcopia = document.querySelector('.copia');
    btexpcsv = document.querySelector('.expcsv');
    btimpcsv = document.querySelector('.impcsv');
    btrexe = document.querySelector('.rexe');
    const ckaudio = document.getElementById('siaudio');
    const ckiframe = document.getElementById('siiframe');
    const ckvideo = document.getElementById('sivideo');
    const ckimxgx = document.getElementById('siimxgx');
    fileInputhtml.addEventListener('change', function() {
        var a = [];
        const files = fileInputhtml.files;
        lerFicheirosHtml();
    });
    fileInputcsv.addEventListener('change', function() {
        var a = [];
        const files = fileInputcsv.files;
        lerFicheiroCsv();
    });
    btexpcsv.addEventListener("click", function() {
        pasarcsv(datosPaxinas);
    });
    btimpcsv.addEventListener("click", function() {
        fileInputcsv.click();
    });
    btrexe.addEventListener("click", function() {
        crearcodigo(datosPaxinas);
    });
    if (document.querySelector('.rhtml')) {
        document.querySelector('.rhtml').addEventListener("click", function() {
            procesaCreditos();
        });
    }
    btgardacode.addEventListener("click", function() {
        codeafile();
    });
    btconf.addEventListener("click", function() {
        contConf.classList.toggle("visibleTempl");
    });
    btlimp.addEventListener("click", function() {
        document.querySelector('.textcode').value = "";
    });
    btabrir.addEventListener("click", function() {
        fileInputhtml.click();
    });
    var axuda = document.getElementById("axudaModal");
    var abriraxuda = document.querySelector('.axuda');
    var pecharaxuda = document.querySelector(".pecharAxuda")
    abriraxuda.addEventListener("click", function() {
        axuda.classList.toggle("visibleAxuda");
    });
    pecharaxuda.addEventListener("click", function() {
        axuda.classList.toggle("visibleAxuda");
    });
    window.addEventListener("click", function(event) {
        if (event.target == axuda) {
            axuda.classList.toggle("visibleAxuda");
        }
    });
    btselconf.addEventListener('change', function() {
        selectconf();
    });
    siaudio.addEventListener('change', function() {
        crearcodigo(datosPaxinas);
    });
    sivideo.addEventListener('change', function() {
        crearcodigo(datosPaxinas);
    });
    siiframe.addEventListener('change', function() {
        crearcodigo(datosPaxinas);
    });
    siimxgx.addEventListener('change', function() {
        crearcodigo(datosPaxinas);
    });
    btcopia.addEventListener('click', function() {
        txtcode = document.querySelector('.textcode');
        if ((txtcode.value).length > 1) {
            txtcode.select();
            try {
                document.execCommand("copy");
                alert('Os códigos copiáronse ao portapapeis');
            } catch (err) {
                alert("Non foi posible copiar os códigos ao portapapeis:", err);
            }
            txtcode.setSelectionRange(0, 0);
        }
    });
    docurl = document.URL.substring(0, document.URL.lastIndexOf("/"));
    loadconf();
});

function codeafile() {
    if (document.getElementById('codigo').value.length > 1) {
        downloadCodes('creditos.txt', document.getElementById('codigo').value);
    }
}

function downloadCodes(filename, txt) {
    let el = document.createElement('a');
    el.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(txt));
    el.setAttribute('download', filename);
    el.style.display = 'none';
    document.body.appendChild(el);
    el.click();
    document.body.removeChild(el);
}

function loadconf() {
    var listconf = document.querySelector(".selconf");
    for (let i = 0; i < codigos.length; i++) {
        let opt = document.createElement("option");
        opt.text = codigos[i].nome;
        opt.value = codigos[i].nome;
        listconf.options.add(opt);
    }
    document.querySelector(".selconf").selectedIndex = 0;
    selectconf();
}

function quitaFile(arrFiles, key, value) {
    const index = arrFiles.findIndex(obj => obj[key] === value);
    return index >= 0 ? [...arrFiles.slice(0, index), ...arrFiles.slice(index + 1)] : arrFiles;
}

function selectconf() {
    var n = document.querySelector(".selconf").selectedIndex;
    document.querySelector("#tplnivel1").value = codigos[n].nivel1;
    document.querySelector("#tplnivel2").value = codigos[n].nivel2;
    document.querySelector("#tplnivel3").value = codigos[n].nivel3;
    document.querySelector("#tpldef").value = codigos[n].base;
    crearcodigo(datosPaxinas);
}

function lerFicheirosHtml() {
    const cargaFicheiros = document.getElementById('cargaFicheiroshtml');
    const listaNomes = [];
    const datosFicheiros = {};
    var n = 0;
    var listaFicheiros = cargaFicheiros.files;
    var seguir = false;
    var tptalpax = listaFicheiros.length;
    for (let i = 0; i < listaFicheiros.length; i++) {
        if (listaFicheiros[i].name == "index.html") seguir = true;

    };
    if (seguir) {
        for (let i = 0; i < listaFicheiros.length; i++) {

            if ((listaFicheiros[i].name != "crditos.html") && (listaFicheiros[i].name != "crditos_e_descarga.html") && (listaFicheiros[i].name != "crditos_y_descarga.html")) {

                const arquivo = listaFicheiros[i];
                listaNomes.push(listaFicheiros[i].name);
                const reader = new FileReader();
                reader.onload = function(e) {
                    const contenidoHTML = e.target.result;
                    n++;
                    datosFicheiros[reader.nomfich] = contenidoHTML;
                    if (n === tptalpax) {
                        lerIndice(datosFicheiros, listaNomes);
                    }
                };
                reader.nomfich = arquivo.name;
                reader.readAsText(arquivo);
            } else {
                n++;
            }

        }
    } else {
        codigo.value = "Na lista de arquivos non existe index.html, repita a carga de arquivos e comprobe que index.html está entre os seleccionados.";
    }
}

function lerFicheiroCsv() {
    const listaFicheiro = document.getElementById('cargaFicheiroscsv');
    const Ficheiro = listaFicheiro.files[0];
    const reader = new FileReader();
    reader.onload = function(e) {
        const contenidoCSV = e.target.result;
        prodcsv(contenidoCSV);
    };
    reader.readAsText(Ficheiro);
}

function lerIndice(datosFicheiros, listaHTML) {
    datosPaxinas = [];
    //datosPaxinas2 = [];
    var aa = [];
    const texto = Object.values(datosFicheiros)[0]
    const parser = new DOMParser();
    const doc = parser.parseFromString(texto, 'text/html');
    const menu = doc.getElementById('siteNav');
    const listaindex = menu.getElementsByTagName('a');
    const ligasURL = Array.from(listaindex).map(function(a) {
        return {
            url: a.href.replace(/^.*[\\/]/, ''),
            titulopax: a.textContent
        }
    });
    for (let i = 0; i < listaHTML.length; i++) {
        let antarr = procesarHTML(datosFicheiros[ligasURL[i].url], ligasURL[i].titulopax, i, 0);
        datosPaxinas = datosPaxinas.concat(antarr);
        // datosPaxinas2.push(antarr);
    }

    crearcodigo(datosPaxinas);
}

function eliminarDuplicados(array) {
    return array.reduce((dImx, cuImx) => {
        const x = dImx.find(item => item.Nome === cuImx.Nome);
        if (!x) {
            return dImx.concat([cuImx]);
        } else {
            return dImx;
        }
    }, []);
}

function chkurl(fnome) {
    fnome = fnome.replace(docurl, '');
    let rres = fnome;
    if (fnome.substring(0, 4) != "http") {
        rres = fnome.substring(fnome.lastIndexOf('/') + 1)
    }
    return rres;
}

function adddir(fnome) {
    let rres = fnome;
    if (fnome.substring(0, 4) != "http") {
        rres = 'resources/' + fnome.substring(fnome.lastIndexOf('/') + 1)
    }
    return rres;
}

function decodificarTextos(string) {
    try {
        let novoString = string
            .replace(/%E1/g, 'á')
            .replace(/%E9/g, 'é')
            .replace(/%ED/g, 'í')
            .replace(/%F3/g, 'ó')
            .replace(/%FA/g, 'ú')
            .replace(/%C1/g, 'Á')
            .replace(/%C9/g, 'É')
            .replace(/%CD/g, 'Í')
            .replace(/%D3/g, 'Ó')
            .replace(/%DA/g, 'Ú')
            .replace(/%F1/g, 'ñ')
            .replace(/%D1/g, 'Ñ')
            .replace(/%FC/g, 'ü')
            .replace(/%DC/g, 'Ü');
        return decodeURIComponent(novoString);
    } catch (error) {
        return string;
    }
}

function extractdatos(obxecto, tipomd, nm, titupax, modo) {
    nm = nm + 1;
    var dlicenza, obauttx, obautweb, obtittx, obtitweb, oblictx, oblicweb = ''
    var obaut, obtit, oblic, oblip = null;
    var nodeP = obxecto.parentNode;
    if (nodeP.rel) {
        nodeP = nodeP.parentNode;
    }

    if (nodeP.nodeName.toLowerCase() == 'figure') {
        if (nodeP.querySelector('[class="figcaption"]')) {
            dlicenza = nodeP.querySelector('[class="figcaption"]').outerHTML;

            var datfig = nodeP.querySelector('[class="figcaption"]');

            obaut = datfig.querySelector('.author');

            obtit = datfig.querySelector('.title');
            oblic = datfig.querySelector('.license a');
            oblip = datfig.querySelector('.license .custom-license');


            if (obaut) {
                if (obaut.textContent) obauttx = obaut.textContent || "";
                if (obaut.href) obautweb = chkurl(obaut.href) || "";
            }
            if (obtit) {
                if (obtit.textContent) obtittx = obtit.textContent || "";
                if (obtit.href) obtitweb = chkurl(obtit.href) || "";
            }
            if (oblic) {
                if (oblic.textContent) oblictx = oblic.textContent || "";
                if (oblic.href) oblicweb = chkurl(oblic.href) || "";
            }
            if (oblip) {
                if (oblip.parentNode.nodeName.toLowerCase() === 'a') {
		    oblictx = oblip.parentNode.textContent || "";
                    oblicweb = chkurl(oblip.parentNode.href) || "";
                } else {
		    if (oblip.textContent) oblictx = oblip.textContent || "";
                    oblicweb = "-";
                }

            }
        }
    }


    if (obxecto.src.includes('geogebra')) tipomd = 'iframeG';

    if (!obxecto.title) obxecto.title = "";
    if (!obxecto.alt) obxecto.alt = "";
    if (!obtittx) obtittx = obxecto.title;
    var obx = {
        Paxina: nm,
        Titulo_Paxina: titupax,
        Tipo: tipomd,
        Nome: chkurl(obxecto.src),
        Descricion: obxecto.alt,
        Titulo: obxecto.title,
        Autoria: obauttx,
        Web_autoria: obautweb,
        Lenda: obtittx,
        Web_lenda: obtitweb,
        Licenza: oblictx,
        Web_licenza: oblicweb,
        Visible: 1
    };

    if (modo == 1) obx.Visible = 0;
    if (obxecto.title.toLowerCase().includes("(arasaac)")) {
        obx.Autoria = "Sergio Palao";
        obx.Licenza = "CC BY-NC-SA 4.0";
        obx.Web_licenza = "https://creativecommons.org/licenses/by-nc-sa/4.0/deed.gl";
        obx.Visible = 1;
        // if (modo==1){ obx.Visible = 1}else{obx.Visible = 0};
    }
    if (obxecto.title.toLowerCase().includes("(creagal)")) {

        obx.Titulo = obx.Titulo.replace(/\(creagal\)/ig, '').trim();
        obx.Descricion = obx.Descricion.replace(/\(creagal\)/ig, '').trim();
        obx.Lenda = obx.Lenda.replace(/\(creagal\)/ig, '').trim();
        obx.Autoria = "Elaboración propia (proxecto cREAgal)";
        obx.Licenza = "CC BY-NC-SA 4.0";
        obx.Web_licenza = "https://creativecommons.org/licenses/by-nc-sa/4.0/deed.gl";
        obx.Visible = 1;
    }
    if (obxecto.alt.toLowerCase().includes("(arasaac)")) {
        obx.Autoria = "Sergio Palao";
        obx.Licenza = "CC BY-NC-SA 4.0";
        obx.Web_licenza = "https://creativecommons.org/licenses/by-nc-sa/4.0/deed.gl";
        obx.Visible = 1;
        // if (modo==1){ obx.Visible = 1}else{obx.Visible = 0};
    }
    if (obxecto.alt.toLowerCase().includes("(creagal)")) {
        obx.Titulo = obx.Titulo.replace(/\(creagal\)/ig, '').trim();
        obx.Descricion = obx.Descricion.replace(/\(creagal\)/ig, '').trim();
        obx.Lenda = obx.Lenda.replace(/\(creagal\)/ig, '').trim();
        obx.Autoria = "Elaboración propia (proxecto cREAgal)";
        obx.Licenza = "CC BY-NC-SA 4.0";
        obx.Web_licenza = "https://creativecommons.org/licenses/by-nc-sa/4.0/deed.gl";
        obx.Visible = 1;
    }
    if (tipomd == 'iframeG') {

        obx.Titulo = "GeoGebra";
        obx.Nome = urliframeGeoG(obx.Nome);
    }
    if (tipomd == 'iframe') {
        obx.Web_lenda = obx.Nome;
    }
    return obx;
}

function procesarLK(arraymedia, tipomd, nm, titupax) {
    nm = nm + 1;
    var arrG = [];
    arraymedia.forEach(obxecto => {
        var dlicenza, obauttx, obautweb, obtittx, obtitweb, oblictx, oblicweb = ''
        var obaut, obtit, oblic = null;
        if (obxecto.parentNode.nodeName.toLowerCase() == 'figure') {
            if (obxecto.parentNode.querySelector('.figcaption')) {
                dlicenza = obxecto.parentNode.querySelector('.figcaption').outerHTML;
                var datfig = obxecto.parentNode.querySelector('.figcaption');
                obaut = datfig.querySelector('.author');
                obtit = datfig.querySelector('.title');
                oblic = datfig.querySelector('.license a');
                if (obaut) {
                    if (obaut.textContent) obauttx = obaut.textContent || "";
                    if (obaut.href) obautweb = chkurl(obaut.href) || "";
                }
                if (obtit) {
                    if (obtit.textContent) obtittx = obtit.textContent || "";
                    if (obtit.href) obtitweb = chkurl(obtit.href) || "";
                }
                if (oblic) {
                    if (oblic.textContent) oblictx = oblic.textContent || "";
                    if (oblic.href) oblicweb = chkurl(oblic.href) || "";
                }
            }
        }
        if (!obtittx) obtittx = obxecto.title;
        var obx = {
            Paxina: nm,
            Titulo_Paxina: titupax,
            Tipo: tipomd,
            Nome: chkurl(obxecto.href),
            Descricion: obxecto.alt,
            Titulo: obxecto.title,
            Autoria: obauttx,
            Web_autoria: obautweb,
            Lenda: obtittx,
            Web_lenda: obtitweb,
            Licenza: oblictx,
            Web_licenza: oblicweb,
            Visible: 1
        };
        arrG.push(obx);
    })
    return arrG;
}

function procesarGeoG(arrGeoG, tipo, nm, titupax) {
    nm = nm + 1;
    var aut, webaut, titgeo = "";
    var arrG = [];
    arrGeoG.forEach(elem => {
        var ige = elem.className.replace("auto-geogebra auto-geogebra-", "");
        aige = ige.split(" ");
        ige = aige[0];
		var t = "";
		if (elem.querySelector('.auto-geogebra-author')){
         t = decodificarTextos(elem.querySelector('.auto-geogebra-author').innerHTML);
	    }
        var b = t.split(',');
        aut = b[0] || "";
        webaut = b[1]  || "";
        titgeo = b[2]  || "";

        var obx = {
            Paxina: nm,
            Titulo_Paxina: titupax,
            Tipo: tipo,
            Nome: ige,
            Descricion: "",
            Titulo: "GeoGebra",
            Autoria: aut,
            Web_autoria: webaut,
            Lenda: titgeo,
            Web_lenda: webaut,
            Licenza: "",
            Web_licenza: "",
            Visible: 1
        };
        if ((tipo == "iframeG") && (obx.Web_lenda != "")) {
            obx.Web_lenda = "https://www.geogebra.org/m/" + ige;
        }
        arrG.push(obx);
    })
    return arrG;
}

function procesarLB(htmldoc, tipo, nm, titupax) {
    nm = nm + 1;
    const elementosLB = htmldoc.querySelectorAll('a[rel="lightbox"]');
    var arrL = [];
    elementosLB.forEach(elem => {
        const ficheiro = elem.href.substring(elem.href.lastIndexOf('/') + 1)
        var obx = {
            Paxina: nm,
            Titulo_Paxina: titupax,
            Tipo: tipo,
            Nome: ficheiro,
            Descricion: "",
            Titulo: "",
            Autoria: "",
            Web_autoria: "",
            Lenda: "",
            Web_lenda: "",
            Licenza: "",
            Web_licenza: "",
            Visible: 1
        };
        arrL.push(obx);
    })
    return arrL;
}

function reconocerGeog(datos) {
    let fingeoG = [];
    let idgeoG = [];
    let iframesGeoGebra = [];
    idgeoG = datos.querySelectorAll('.iDevice_content > .auto-geogebra');
    const iframes = datos.querySelectorAll('iframe');
    iframesGeoGebra = Array.from(iframes).filter(iframe => {
        return iframe && iframe.src.includes('geogebra');
    });

    fingeoG = Array.from(idgeoG).concat(iframesGeoGebra);
    return fingeoG;
}

function reconocerIframe(datos) {
    const iframes = datos.querySelectorAll('iframe');
    const iframesI = Array.from(iframes).filter(iframe => {
        return iframe && !iframe.src.includes('geogebra');
    });
    return iframesI
}

function urliframeGeoG(url) {
    const partes = url.split('/id/');
    if (partes.length >= 2) {
        const valorId = partes[1].split('/')[0];
        return partes[0] + '/id/' + valorId;
    }
    return '';
}

function procesarHTML(textoHTML, nomeurlpax, index, modo) {
    var datosObx = {}
    const parser = new DOMParser();
    const doc = parser.parseFromString(textoHTML, 'text/html');
    var datosObx = [];
    var nomepax = "n";
    if (doc.querySelector('#nodeTitle')) nomepax = doc.querySelector('#nodeTitle').textContent || "n";
    const arrgamesIm = doc.querySelectorAll('[class*="-LinkImages"]')
    const arrgamesAu = doc.querySelectorAll('[class*="-LinkAudios"]')
    const arrLK = [...arrgamesIm,...arrgamesAu]
    var arrGeo = doc.querySelectorAll('.iDevice_content > .auto-geogebra')
    //const arrGeo = reconocerGeog(doc);
    const imaxes = doc.getElementsByTagName('img');
    const datosImaxes = Array.from(imaxes).map(function(img) {
        return extractdatos(img, 'imaxe', index, nomepax);
    });
    var regexMedia = /\.(jpg|jpeg|png|svg|gif|webp)$/i;
    var valLK = arrLK.filter(elem => regexMedia.test(elem))
    const datosImaxesG = procesarLK(valLK, 'imaxe', index, nomepax);
    const datosImaxesLB = procesarLB(doc, 'imaxe', index, nomepax);
    var datosImaxesL = datosImaxes.concat(datosImaxesLB);
    var datosImaxesf = datosImaxesL.concat(datosImaxesG);
    var datosImaxesU = eliminarDuplicados(datosImaxesf);
    const videos = doc.querySelectorAll('video source');
    const datosVideos = Array.from(videos).map(function(video) {
        return extractdatos(video, 'video', index, nomepax, modo);
    });
    var regexMedia = /\.(mp4|webm)$/i;
    var valLK = arrLK.filter(elem => regexMedia.test(elem))
    const datosVideosG = procesarLK(valLK, 'video', index, nomepax);
    const datosVideosf = datosVideos.concat(datosVideosG);
    const datosVideosU = eliminarDuplicados(datosVideosf);
    const audios = doc.querySelectorAll('audio');
    const datosAudios = Array.from(audios).map(function(audio) {
        return extractdatos(audio, 'audio', index, nomepax);
    });
    var regexMedia = /\.(wav|mp3|ogg)$/i;
    var valLK = arrLK.filter(elem => regexMedia.test(elem))
    const datosAudiosG = procesarLK(valLK, 'audio', index, nomepax);
    const datosAudiosf = datosAudios.concat(datosAudiosG);
    const datosAudiosU = eliminarDuplicados(datosAudiosf);
    //const iframes = reconocerIframe(doc);


    /*
     const datosIframes = Array.from(iframes)
    .filter(iframe => !iframe.src.includes('geogebra'))
    .map(function(iframe) {
        return (iframe, 'iframe', index, nomepax);
    });
    * */
    const iframes = doc.querySelectorAll('iframe');
    const datosIframes = Array.from(iframes).map(function(iframe) {
        return extractdatos(iframe, 'iframe', index, nomepax);
    });



    var arrGb = procesarGeoG(arrGeo, 'iframeG', index, nomepax);
    const datosIframesf = datosIframes.concat(arrGb);
    const datosIframesU = eliminarDuplicados(datosIframesf);
    modo = 0;
    datosObx = datosObx.concat(datosImaxesU);
    if (modo == 0) {
        if (typeof datosVideosU !== 'undefined') datosObx = datosObx.concat(datosVideosU);
        if (typeof datosAudiosU !== 'undefined') datosObx = datosObx.concat(datosAudiosU);
        if (typeof datosIframesU !== 'undefined') datosObx = datosObx.concat(datosIframesU);
    }
    if (datosObx.length == 0) {
        if (index == 0) index = 1;
        datosObx = [{
            Paxina: index,
            Titulo_Paxina: nomepax,
            Tipo: '*',
            Nome: "",
            Descricion: "",
            Titulo: "",
            Autoria: "",
            Web_autoria: "",
            Lenda: "",
            Web_lenda: "",
            Licenza: "",
            Web_licenza: "",
            Visible: 1
        }]
    }
    return datosObx;
}
async function procesaCreditos() {
    datosPaxinas = [];
    await datosCreditos('txhtml');
    /*
    if (document.getElementById('txhtml2').value != "") {
        await datosCreditos('txhtml2');
    }
    * */
    crearcodigo(datosPaxinas);
}

function datosCreditos(donde) {
    const contenttxt = document.getElementById(donde).value;
    const parser = new DOMParser();
    const content = parser.parseFromString(contenttxt, 'text/html');
    const headings = content.querySelectorAll('h2');
    const tempDiv = document.createElement('div');
    const sections = [];
    headings.forEach((heading, index) => {
        const nextHeading = headings[index + 1] || content.lastElementChild;
        const range = document.createRange();
        range.setStartAfter(heading);
        range.setEndBefore(nextHeading);
        const section = range.extractContents();
        sections.push(section);
        tempDiv.innerHTML = "";
        tempDiv.appendChild(section);
        const htmlString = tempDiv.outerHTML;
        let antarr = procesarHTML(tempDiv.innerHTML, 'no titulo', index, 0);
        datosPaxinas = datosPaxinas.concat(antarr);
    });
}

function creamedia(codhtml, inimedia, finmedia, nome, titulo, descricion) {
    if (nome.indexOf("data:") == -1) {
        nome = adddir(nome);
    }
    if (titulo) {
        if (titulo.toLowerCase().includes('(arasaac)')) {
            titulo = titulo.replace(/\(arasaac\)/ig, '').trim();
        }
        if (titulo.toLowerCase().includes('(creagal)')) {
            titulo = titulo.replace(/\(creagal\)/ig, '').trim();
        }
    }
    if (descricion) {
        if (descricion.toLowerCase().includes('(arasaac)')) {
            descricion = descricion.replace(/\(arasaac\)/ig, '').trim();
        }

        if (descricion.toLowerCase().includes('(creagal)')) {
            descricion = descricion.replace(/\(creagal\)/ig, '').trim();
        }
    }
    codhtml = codhtml.replace("[[#multimedia]]", inimedia);
    codhtml = codhtml.replace("[[multimedia#]]", finmedia);
    codhtml = codhtml.replace(/{{title}}/g, titulo);
    codhtml = codhtml.replace("{{imx}}", nome);
    codhtml = codhtml.replace(/{{imxalt}}/g, descricion);
    return codhtml;
}

function crearcodigo(bruto) {
    if (bruto.length > 0) {
        const siaudio = document.getElementById('siaudio').checked;
        const siiframe = document.getElementById('siiframe').checked;
        const siimxgG = siimxgx.checked;
        const sivideo = document.getElementById('sivideo').checked;
        var modcreagal = 0;
        var nungeogebra = 0;
        let tpl = document.getElementById('tplnivel2').value;
        let tpldef = document.getElementById('tplnivel3').value;
        let tplbase = document.getElementById('tplnivel1').value;
        let tmpdat = document.getElementById('tpldef').value;
        if (btselconf.value.indexOf('cREAgal') > -1) modcreagal = 1;
        if (tmpdat) {
            var tpldat = document.getElementById('tpldef').value.split("|");
        } else {
            var tpldat = ["--", "", "--", "", "--", "--"];
        }
        tpldat.map((item) => {
            if (item === undefined) return "--";
        });
        var textxtermo = '';
        var ni = 0;
        var datos = [];
        var npax = Number(bruto[bruto.length - 1].Paxina);
        for (let i = 0; i < npax; i++) {
            datos[i] = [];
        }
        for (let i = 0; i < bruto.length; i++) {
            npax = Number(Number(bruto[i].Paxina) - 1);
            datos[npax].push(bruto[i]);
        }
        for (let i = 0; i < datos.length; i++) {
            var atpl = tpl;
            var atpldefsum = '';
            var ct = 0;
            for (let z = 0; z < datos[i].length; z++) {
                if (datos[i][z].Tipo != "*") {
                    Object.keys(datos[i][z]).forEach(function(key, index) {
                        if (datos[i][z][key] === undefined) datos[i][z][key] = "";
                        if (datos[i][z][key] === null) datos[i][z][key] = "";
                    });
                    let nfich = datos[i][z].Nome.replace(/\.[^/.]+$/, '');
                    if (nfich.substring(nfich.length - 4) != '-non') {
                        if (datos[i][z].Visible != 0) {
                            atpldef = tpldef;
                            ct++;
                            if (ct > 3) {
                                ct = 1;
                            }
                            atpldef = atpldef.replace("{{numcol}}", ct);
                            if (datos[i][z].Tipo == "imaxe") {
                                atpldef = creamedia(atpldef, "<img", "/>", datos[i][z].Nome, datos[i][z].Titulo, datos[i][z].Descricion);
                            } else if (datos[i][z].Tipo == "audio") {

                                if (siaudio) {
                                    atpldef = creamedia(atpldef.replace('width:auto', 'width:98%'), "<audio", " controls='controls' ></audio>", datos[i][z].Nome, datos[i][z].Titulo, datos[i][z].Descricion);
                                } else {
                                    atpldef = creamedia(atpldef, "<img", " style='border: 1px solid red; width: 98%; height: 190px;background-color:#00CAFF'/>", '', 'Audio', 'Audio');
                                }
                            } else if (datos[i][z].Tipo == "video") {
                                if (sivideo) {
                                    atpldef = creamedia(atpldef, "<video", " controls='controls' ></video>", datos[i][z].Nome, datos[i][z].Titulo, datos[i][z].Descricion);
                                } else {
                                    atpldef = creamedia(atpldef, "<img", " style='border: 1px solid red; width: 98%; height: 190px;background-color:#00CAFF'/>", '', 'Vídeo', 'Vídeo');
                                }
                            } else if (datos[i][z].Tipo == "iframe") {
                                if (siiframe) {
                                    atpldef = creamedia(atpldef, "<iframe", "data-mce-fragment='1'></iframe>", datos[i][z].Nome, datos[i][z].Titulo, datos[i][z].Descricion);
                                } else {
                                    atpldef = creamedia(atpldef, "<img", " style='border: 1px solid red; width: 98%; height: 190px;background-color:#00CAFF'/>", '', datos[i][z].Nome, datos[i][z].Descricion);
                                }
                            } else if (datos[i][z].Tipo == "iframeG") {
                                if (!siimxgG) {
                                    var urlgeoG = 'https://www.geogebra.org/material/iframe/id/';
                                    if (datos[i][z].Nome.startsWith("http")) urlgeoG = '';
                                    atpldef = creamedia(atpldef, "<iframe", "data-mce-fragment='1'></iframe>", urlgeoG + datos[i][z].Nome, datos[i][z].Titulo, datos[i][z].Descricion);
                                } else {
                                    //atpldef = creamedia(atpldef, "<a href='https://www.geogebra.org/m/"+ datos[i][z].Nome+"' target='_blank'><img", "/></a>", "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' height='30' width='200'><text x='8' y='22'>G⊾</text></svg>", datos[i][z].Nome);
                                    atpldef = creamedia(atpldef, "<img", " style='border: 1px solid red; width: 98%; height: 190px;background-color:#00CAFF'/>", "unnamed.png", datos[i][z].Titulo, datos[i][z].Descricion);
                                }
                            }
                            if ((datos[i][z].Titulo.toLowerCase().includes('(arasaac)')) || (datos[i][z].Descricion.toLowerCase().includes('(arasaac)')) || (datos[i][z].Lenda.toLowerCase().includes('Pictograma de ARASAAC'))) {
                                const regex = new RegExp(`${'<figcaption'}(.*?)${'</figcaption>'}`, 'g');
                                atpldef = atpldef.replace(regex, '<figcaption class="figcaption">Pictograma de ARASAAC</figcaption>');
                            } //else if ((datos[i][z].Autoria.includes('(proxecto cREAgal)'))|| (datos[i][z].Titulo.toLowerCase().includes('(creagal)')) || (datos[i][z].Descricion.toLowerCase().includes('(creagal)'))) {
                            else if ((datos[i][z].Titulo.toLowerCase().includes('(creagal)')) || (datos[i][z].Descricion.toLowerCase().includes('(creagal)'))) {
                                const regex = new RegExp(`${'<figcaption'}(.*?)${'</figcaption>'}`, 'g');
                                atpldef = atpldef.replace(regex, '<figcaption class="figcaption"><span class="author">Elaboración propia (proxecto cREAgal)</span>. <span class="title"><em>' + datos[i][z].Lenda + '</em> </span><span class="license"><span class="sep">(</span><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.es" rel="license nofollow noopener" target="_blank" title="CC BY-NC-SA 4.0">CC BY-NC-SA 4.0</a><span class="sep">)</span></span></span></figcaption>');
                            } else if ((datos[i][z].Autoria.toLowerCase().includes('(celtia)')) || (datos[i][z].Descricion.toLowerCase().includes('(celtia)')) || (datos[i][z].Lenda.toLowerCase().includes('modelo Celtia'))) {
                                const regex = new RegExp(`${'<figcaption'}(.*?)${'</figcaption>'}`, 'g');
                                atpldef = atpldef.replace(regex, '<figcaption class="figcaption"><span class="author">Elaboración propia (proxecto cREAgal) con apoio de IA, voz sintética xerada co modelo Celtia</span>. <span class="title"><em>' + datos[i][z].Lenda + '</em> </span><span class="license"><span class="sep">(</span><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.es" rel="license nofollow noopener" target="_blank" title="CC BY-NC-SA 4.0">CC BY-NC-SA 4.0</a><span class="sep">)</span></span></span></figcaption>');
                            } else if ((datos[i][z].Titulo.toLowerCase().includes('(Sabela)')) || (datos[i][z].Descricion.toLowerCase().includes('(sabela)')) || (datos[i][z].Lenda.toLowerCase().includes('modelo Sabela'))) {
                                const regex = new RegExp(`${'<figcaption'}(.*?)${'</figcaption>'}`, 'g');
                                atpldef = atpldef.replace(regex, '<figcaption class="figcaption"><span class="author">Elaboración propia (proxecto cREAgal), voz sintética xerada co modelo Sabela</span>. <span class="title"><em>' + datos[i][z].Lenda + '</em> </span><span class="license"><span class="sep">(</span><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.es" rel="license nofollow noopener" target="_blank" title="CC BY-NC-SA 4.0">CC BY-NC-SA 4.0</a><span class="sep">)</span></span></span></figcaption>');
                            } else if (datos[i][z].Tipo == "iframeG") {
                                const regex = new RegExp(`${'<figcaption'}(.*?)${'</figcaption>'}`, 'g');
                                nungeogebra++;
                                var urlgeoG = 'https://www.geogebra.org/material/iframe/id/';
                                if (datos[i][z].Nome.startsWith("http")) urlgeoG = '';
                                if (datos[i][z].Lenda == "") datos[i][z].Lenda = "GeoGebra" + nungeogebra;
                                var txautgG = '<span class="author">Elaboración propia (proxecto cREAgal)</span>';
                                if (datos[i][z].Autoria != '') txautgG = '<a href="' + datos[i][z].Web_autoria + '" target="_blank" class="author" rel="noopener">' + datos[i][z].Autoria + '</a>';


                                atpldef = atpldef.replace(regex, '<figcaption class="figcaption">' + txautgG + '. <a href="' + urlgeoG + datos[i][z].Nome + '" target="_blank" class="title" rel="noopener"><em>' + datos[i][z].Lenda + '</em></a><span class="license"><span class="sep"> (</span><a href="https://www.geogebra.org/license" rel="license nofollow noopener" target="_blank" title="GeoGebra Non-Commercial License">GeoGebra Non-Commercial License</a><span class="sep">)</span></span></span></figcaption>');

                                // <span class="title"><em>' + datos[i][z].Lenda + '</em> </span>
                            } else if (datos[i][z].Web_licenza == "-") {
                                const regex = new RegExp(`${'<figcaption'}(.*?)${'</figcaption>'}`, 'g');

                                atpldef = atpldef.replace(regex, '<figcaption class="figcaption"><a href="' + datos[i][z].Web_autoria + '" target="_blank" class="author" rel="noopener">' + datos[i][z].Autoria + '</a>. <a href="' + datos[i][z].Web_lenda + '" target="_blank" class="title" rel="noopener"><em>' + datos[i][z].Lenda + '</em></a> <span class="license"><span class="sep">(</span><span class="custom-license">' + datos[i][z].Licenza + '</span><span class="sep">)</span></span></figcaption>');

                            } else {

                                if (!datos[i][z].fHtml) {
                                    atpldef = creafigcaption(atpldef, '{{titulo}}', datos[i][z].Lenda, tpldat[2]);
                                    atpldef = creafigcaption(atpldef, '{{web-titulo}}', datos[i][z].Web_lenda, tpldat[3]);
                                    atpldef = creafigcaption(atpldef, '{{web-modlice}}', datos[i][z].Web_licenza, tpldat[5]);
                                    atpldef = creafigcaption(atpldef, '{{modlice}}', datos[i][z].Licenza, tpldat[4]);
                                    atpldef = creafigcaption(atpldef, '{{modlicer}}', datos[i][z].Licenza, tpldat[4].replace('Creative Commons', 'CC'));
                                    atpldef = creafigcaption(atpldef, '{{autor}}', datos[i][z].Autoria, tpldat[0]);
                                    atpldef = creafigcaption(atpldef, '{{web-autor}}', datos[i][z].Web_autoria, tpldat[1]);

                                } else {
                                    atpldef = atpldef.replace("{{licenza}}", datos[i][z].fHtml);
                                }
                            }
                            if (ct == 1 && modcreagal == 1) {
                                atpldef = '<div class="exe-layout-3-cols exe-clear">' + atpldef;
                            }
                            if (ct == 3 && modcreagal == 1) {
                                atpldef = atpldef + '</div>';
                            }
                            atpldefsum = atpldefsum + atpldef;
                        }
                    }
                }
            }
            ni = i + 1;
            if (ct > 0 && ct < 3 && modcreagal == 1) {
                atpldefsum = atpldefsum + '</div>';
            }
            atpl = atpl.replace("{{col3}}", atpldefsum);
            atpl = atpl.replace("{{numero}}", ni.toString());
            textxtermo = textxtermo + atpl;
        }
        textxtermo = '\n' + textxtermo;
        let ahtml = tplbase.replace("{{col2}}", textxtermo);
        let fcode = document.getElementById('codigo');
        fcode.value = ahtml;
    }
}

function creafigcaption(txtplan, clave, valor, def) {
    let txtdev = "";
    valor.replaceAll('"', '');
    if (valor) {
        txtdev = txtplan.replaceAll(clave, valor);
    } else {
        txtdev = txtplan.replaceAll(clave, def);
    }
    return txtdev;
}

function modfig(obj, def) {
    let txtdev = "";
    if (obj == '') {
        txtdev = def;
    } else {
        txtdev = obj;
    }
    return txtdev;
}

function pasarcsv(obxecto) {
    if (obxecto.length > 0) {
        let tmpdat = document.getElementById('tpldef').value;
        if (tmpdat) {
            var tpldat = document.getElementById('tpldef').value.split("|");
        } else {
            var tpldat = ["--", "--", "--", "--", "--", "--"];
        }
        tpldat.map((item) => {
            if (item === undefined) return "--";
        });
        for (let i = 0; i < obxecto.length; i++) {
            obxecto[i].Lenda = modfig(obxecto[i].Lenda, tpldat[2]);
            obxecto[i].Web_lenda = modfig(obxecto[i].Web_lenda, tpldat[3]);
            obxecto[i].Web_licenza = modfig(obxecto[i].Web_licenza, tpldat[5]);
            obxecto[i].Licenza = modfig(obxecto[i].Licenza, tpldat[4]);
            obxecto[i].Autoria = modfig(obxecto[i].Autoria, tpldat[0]);
            obxecto[i].Web_autoria = modfig(obxecto[i].Web_autoria, tpldat[1]);
        }
        const titleKeys = Object.keys(obxecto[0]);
        const refinedData = []
        refinedData.push(titleKeys)
        obxecto.forEach(item => {
            refinedData.push(Object.values(item))
        })
        const csvContent = Papa.unparse(obxecto);
        const nomef = (obxecto[0].Titulo_Paxina.replaceAll(' ', '_')).toLowerCase() || "rea";
        downloadCodes(nomef + '-creditos.csv', csvContent);
    }
}

function astring(valor) {
    return valor.toString();
}

function prodcsv(valor) {
    Papa.parse(valor, {
        header: true,
        dynamicTyping: false,
        complete: function(results) {
            let data = results.data;
            let novoarr = data.filter(obj => {
                return Object.values(obj).some(value => value !== null && value !== undefined && value !== '');
            });
            datosPaxinas = novoarr;
            crearcodigo(novoarr);
        }
    });
}
