$(document).ready(function(){
    /**
     * 
     * @returns 
     */
    $.fn.validations = function(){
        return [
           {
            "name":"noEmpty",
            "message":window.translations["create-patient"].fieldRequired,
            "run":function (field){
                let isRequiredContact = false;
                let isRequiredIdentityNumber = false;
                let age;
                if(field.key === "id") return true;
                if(field.key === "patient_id") return true;
                if(field.key === "age") return true;
                if(field.key === "continueFromAppointment") return true;
                if(field.key === "doctorname") return true;
                if((field.key === "phone") || (field.key === "email")|| (field.key === "address")){
                    age = document.querySelector("#age");
                    isRequiredContact = (parseInt(Number(age.value.trim())) >= 18);
                    if(isRequiredContact){
                        return ((field.value != undefined) && (field.value.trim() !== ""))
                    }
                    return true;
                }
                if((field.key === "identification")){
                    age = document.querySelector("#age");
                    isRequiredIdentityNumber = (parseInt(Number(age.value.trim())) >= 18);
                    if(isRequiredIdentityNumber){
                        return ((field.value != undefined) && (field.value.trim() !== ""))
                    }
                    return true;
                }
                return ((field.value != undefined) && (field.value.trim() !== "")); 
            }
           },
           {
            "name":"noNumber",
            "message":window.translations["create-patient"].fieldMustNumber,
            "run":function (field){
                if(field.key !== "age") return true;
                return (!isNaN(Number(field.value)));
            }
           },
           /*{
            "name":"greaterThanZero",
            "message":window.translations["create-patient"].fieldMustGreaterThanZero,
            "run":function (field){
                if(field.key !== "age") return true;
                return (Number(field.value) > 0);
            }
           },*/
           {
            "name":"validDate",
            "message":window.translations["create-patient"].validDate,
            "run":function(field){
                if(field.key !== "birthday")
                    return true;
                let year  = field.value.split("/")[2];
                let month = field.value.split("/")[1];
                let day = field.value.split("/")[0];
    
                    return (
                        (year !== undefined) && 
                        (month !== undefined) &&
                        (day !== undefined) &&
                        (year.length === 4)&& 
                        (month.length === 2)&& 
                        (day.length === 2)&& 
                        (Number(month) <= 12)&& 
                        (Number(month) > 0)&& 
                        (Number(day) <= 31)&& 
                        (Number(day) > 0));
            }
           }
        ];
    }
    $("#patient").on("submit",function(e){
        let form    = document.querySelector("#patient");
        let data    = $.fn.getDataForm.call(this,form);
        let valid   = $.fn.runValidations(data,$.fn.validations());

        if(!valid.valid)
            e.preventDefault();
    });
    $('#age').on("keydown",(function(e) {
        // Obtener el valor de la tecla presionada
        var key = e.keyCode || e.charCode;
    
        // Permitir las teclas numéricas, de navegación y del teclado numérico derecho
        if (key >= 48 && key <= 57 || key >= 96 && key <= 105 || key == 8 || key == 9 || key == 37 || key == 39) {
            return true;
        }
    
        // Prevenir la entrada de valores no numéricos
        e.preventDefault();
        return false;
    }));


    $('[name="birthday"]').mask('00/00/0000');


    const validateFormatAge = (date)=>{
        const regex = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/\d{4}$/;
        return regex.test(date);
    }

    const  calcuteAge  = (date) => {
        const partsOfDate = date.split("/");
        const day = parseInt(partsOfDate[0], 10);
        const month = parseInt(partsOfDate[1], 10) - 1; // Los meses en JavaScript son 0-11
        const year = parseInt(partsOfDate[2], 10);
        
        const birthday = new Date(year, month, day);
        const currentDate = new Date();
        const currentMonth = currentDate.getMonth();
        const currentDay = currentDate.getDate();
        
        let age = currentDate.getFullYear() - birthday.getFullYear();        
        if (currentMonth < month || (currentMonth === month && currentDay < day)) {
            age--;
        }
        return age;
    }

    $('[name="birthday"]').on("input",(function(e) {
        let input = $('[name="birthday"]').val();
        if(validateFormatAge(input)){
            let age = calcuteAge(input);
            $('#age').val(age).trigger('input');
        }else{
            $('#age').val(null).trigger('input');
        }
    }));

})