import {
    validarContentInput,
    limpiarFormulario,
    notify,
    lastDayOfMonth,
    isFrecuenciaAbsoluta,
    numFrmt,
    valorSemaforo,
    generalStylesSignField,
    uploadPictureToWeb,
    validarContentTextArea,
    deshabilitarInput,
    camposObligatorios,
    currentDate
} from "./functions.js";

const colorSiVacio = "#f48c06";
const colorNoVacio = "#03071e";
const idInicioTrim = "inicioTrim";
const idFinTrim = "finTrim";
const inicioX = document.getElementById("inicioTrim");
const finX = document.getElementById("finTrim");

(() => {
    validarContentInput(idInicioTrim, colorSiVacio, colorNoVacio);
    validarContentInput(idFinTrim, colorSiVacio, colorNoVacio);
})();

// validación de textarea 
(() => {
    validarContentTextArea('infosoporte', colorSiVacio, colorNoVacio);
})();


let inputs = document.getElementsByTagName("input");

for (let i of inputs) {
    validarContentInput(i.id, colorSiVacio, colorNoVacio);
}

let validarInicioDate = (() => {
    inicioX.addEventListener("change", () => {
        let dateIni = String(inicioX.value).split("-");
        let monthIni = parseInt(dateIni[1]);
        let yearIni = parseInt(dateIni[0]);
        if (monthIni == 1 || monthIni == 4 || monthIni == 7 || monthIni == 10) {
            let frmDate;
            switch (monthIni) {
                case 1:
                    frmDate = `${yearIni}-03-${lastDayOfMonth(yearIni, 3)}`;
                    break;
                case 4:
                    frmDate = `${yearIni}-06-${lastDayOfMonth(yearIni, 6)}`;
                    break;
                case 7:
                    frmDate = `${yearIni}-09-${lastDayOfMonth(yearIni, 9)}`;
                    break;
                case 10:
                    frmDate = `${yearIni}-12-${lastDayOfMonth(yearIni, 12)}`;
                    break;
            }
            inicioX.value = `${yearIni}-${numFrmt(monthIni)}-01`;
            finX.value = frmDate;
            finX.style.border = `2px solid ${colorNoVacio}`;
        } else {
            notify(
                "warning",
                "Los trimestres deben iniciar en:" +
                "\n" +
                "1) enero" +
                "\n" +
                "4) abril" +
                "\n" +
                "7) julio" +
                "\n" +
                "10) octubre",
                5000
            );
            inicioX.value = "";
            finX.value = "";
            finX.style.border = `3px solid ${colorSiVacio}`;
        }
    });
})();

let validarFinDate = (() => {
    finX.addEventListener("change", () => {
        let dateFin = String(finX.value).split("-");
        let monthfin = parseInt(dateFin[1]);
        let yearFin = parseInt(dateFin[0]);
        if (monthfin == 3 || monthfin == 6 || monthfin == 9 || monthfin == 12) {
            let frmDate;
            switch (monthfin) {
                case 3:
                    frmDate = `${yearFin}-01-01`;
                    break;
                case 6:
                    frmDate = `${yearFin}-04-01`;
                    break;
                case 9:
                    frmDate = `${yearFin}-07-01`;
                    break;
                case 12:
                    frmDate = `${yearFin}-10-01`;
                    break;
            }
            inicioX.value = frmDate;
            finX.value = `${yearFin}-${numFrmt(monthfin)}-${lastDayOfMonth(
			yearFin,
			monthfin
		)}`;
            inicioX.style.border = `2px solid ${colorNoVacio}`;
        } else {
            notify(
                "warning",
                "Los trimestres deben finalizar en:" +
                "\n" +
                "3) marzo" +
                "\n" +
                "6) junio" +
                "\n" +
                "9) septiembre" +
                "\n" +
                "12) diciembre",
                5000
            );
            inicioX.value = "";
            finX.value = "";
            inicioX.style.border = `3px solid ${colorSiVacio}`;
        }
    });
})();

let btnLimpiarFormulario = (() => {
    let btnLimpiar = document.getElementById("btnLimpiar");
    btnLimpiar.addEventListener("click", () => {
        limpiarFormulario(colorSiVacio);
    });
})();


for (let o of inputs) {
    // cambiar a ternaria

    if (o.id.includes("varA_")) {
        let n = Number(o.id.replace("varA_", ""));

        let varAinput = `varA_${n}`;
        let varBinput = `varB_${n}`;
        let semaforo = `semaforo_${n}`;
        let idCirculo = `circle_${n}`;
        let amarillo_li = `amarillo_li_${n}`;
        let amarillo_ls = `amarillo_ls_${n}`;
        let signo = `signo_${n}`;
        let idUnidadDeMedida = `unidadMedida_${n}`;
        let idTable = `table_${n}`;
        let idMeta = `index_meta_${n}`;
        let rowRojo = `critico_${n}`;
        let rowAmarillo = `riesgo_${n}`;
        let rowVerde = `aceptable_${n}`;

        valorSemaforo(
            varAinput,
            varBinput,
            semaforo,
            idCirculo,
            amarillo_li,
            amarillo_ls,
            signo,
            rowRojo,
            rowAmarillo,
            rowVerde
        );
    }
}


let btnImprimir = (() => {
    let btnPrint = document.getElementById('btnPrint');

    btnPrint.addEventListener('click', () => {

        let r = 0;
        let inputTags = document.getElementsByTagName("input");
        let fieldSoporte = document.getElementById("infosoporte");
        for (let i = 0; i < inputTags.length; i++) {
            if (inputTags[i].value == '' && inputTags[i].disabled == false && inputTags[i].getAttribute('type') != 'file') {
                r += 1;
            }
        }

        if (fieldSoporte.value.length == 0) {
            r += 1;
        }

        if (r > 0) {
            let mensaje;
            if (r == 1) {
                mensaje = "El campo con borde naranja es obligatorio";
            } else {
                mensaje = `Los ${r} campos marcados con borde naranja son obligatorios`;
            }

            notify('warning', mensaje, 5000);
        } else {
            window.print();
        }

    })
})();


(() => {
    let crDate = document.getElementById("currentDate");
    crDate.innerText = currentDate();
})();


(function() {
    // http://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean
    var $ = function(elem) {
        if (!(this instanceof $)) {
            return new $(elem);
        }
        this.el = document.getElementById(elem);
    };
    window.$ = $;
    $.prototype = {
        onChange: function(callback) {
            this.el.addEventListener("change", callback);
            return this;
        },
    };
})();

(() => {
    generalStylesSignField(
        "squareSignFielRepresentante",
        "imgSignRepresentante",
        "fileUploadRepresentante"
    );
    generalStylesSignField(
        "squareSignFielSubCentroSCT",
        "imgSignSubCentroSCT",
        "fileUploadSubCentroSCT"
    );
    // generalStylesSignField('userActionsDos', 'imgPrimeDos', 'fileUploadDos');

    uploadPictureToWeb(
        "squareSignFielRepresentante",
        "fileUploadRepresentante",
        "imgSignRepresentante"
    );
    uploadPictureToWeb(
        "squareSignFielSubCentroSCT",
        "fileUploadSubCentroSCT",
        "imgSignSubCentroSCT"
    );
    // uploadPictureToWeb('userActions', 'fileUpload', 'imgPrime');
    // uploadPictureToWeb('userActionsDos', 'fileUploadDos', 'imgPrimeDos');
})();

// bloqueo de los campos sin variable de cálculo
(() => {

    if (parseInt(nIndicadores) > 0) {

        let nI = parseInt(nIndicadores);
        let e = 1;

        for (; e <= nI; e++) {

            let varA = document.getElementById(`varA${e}Strong`);
            let inputA = `varA_${e}`;
            let varB = document.getElementById(`varB${e}Strong`);
            let inputB = `varB_${e}`;
            let idUnidadDeMedida = `unidadMedida_${e}`;
            let idCirculo = `circle_${e}`
            let idTable = `table_${e}`;
            let idMeta = `index_meta_${e}`;
            `${varA.textContent}`.replace('\n', '').trim().length <= 1 ? deshabilitarInput(inputA) : varA;
            `${varB.textContent}`.replace('\n', '').trim().length <= 1 ? deshabilitarInput(inputB) : varB;
            isFrecuenciaAbsoluta(idUnidadDeMedida, idCirculo, idTable, idMeta);
            validarContentInput(inputA, colorSiVacio, colorNoVacio)
            validarContentInput(inputB, colorSiVacio, colorNoVacio)

        }

        notify("success", `${camposObligatorios()}`, 7000)
    } else {
        notify("warning", "No se han cargado los indicadores de la Aldea Inteligente.", 7000)
    }

})()






// idea de descargar la página web:
// https://www.youtube.com/watch?v=C8jxInLM9nM&ab_channel=PrettyPrinted


// grillado de galeria
// https://codepen.io/eHtmlu/pen/BaodGVp