$(document).ready(function(){
     /**
     * 
     * @returns 
     */
     $.fn.validations = function(){
        return [
           {
            "name":"noEmpty",
            "message":window.translations["update-patient"].fieldRequired,
            "run":function (field){
                let isRequiredContact = false;
                let isRequiredIdentityNumber = false;
                if(field.key === "id") return true;
                if(field.key === "patient_id") 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["update-patient"].fieldMustNumber,
            "run":function (field){
                if(field.key !== "age") return true;
                return (!isNaN(Number(field.value)));
            }
           },
           /*{
            "name":"greaterThanZero",
            "message":window.translations["update-patient"].fieldMustGreaterThanZero,
            "run":function (field){
                if(field.key !== "age") return true;
                return (Number(field.value) > 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();
    });
    $('[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');
        }
    }));

    $('#age').trigger('input');

});
