var Form = new Form();

/***
 * Gestionnaire de formulaire
 * @returns {Form}
 */
function Form()
{
    /**
     * Vérifie chaque champ du formulaire
     * @param {type} formId
     * @returns 
     */
    this.IsValid = function (formId)
    {
        this.formId = formId;
        var currentForm = document.getElementById(this.formId);
        this.currentForm = currentForm;

        var controls = currentForm.getElementsByTagName("input");
        var textarea = currentForm.getElementsByTagName("textarea");
        var select = currentForm.getElementsByTagName("select");
        var uploaderDiv = currentForm.getElementsByClassName("uploaderDiv");

        var errors = 0;

        //Validation des input standards
        for (var i = 0; i < controls.length; i++) {
            if (!this.VerifyControl(controls[i]))
            {
                errors += 1;
            }
        }

        //Validation des texteare
        for (var i = 0; i < textarea.length; i++) {
            if (!this.VerifyControl(textarea[i]))
            {
                errors += 1;
            }
        }

        /**
         * Validation des selection
         */
        for (var i = 0; i < select.length; i++) {
            if (!this.VerifyControl(select[i]))
            {
                errors += 1;
            }
        }

        for (var i = 0; i < uploaderDiv.length; i++) {
            if (!this.VerifiyUpload(uploaderDiv[i]))
            {
                errors += 1;
            }
        }

        return (errors == 0);
    };

    /**
     * Vérifie le control selon ces validators
     * @returns 
     */
    this.VerifyControl = function (control) {

        if (control.dataset.validator == undefined) {
            return true;
        }

        var validators = control.dataset.validator.split("|");

        this.RemoveErrorMessage(control);

        //Enfin on vérifie le type
        if (!this.VerifyType(control)) {
            this.AddErrorMessage(control, "IncorrectFormat");
            return false;
        }

        if (validators != "undefined") {

            //On verifie chaque validator
            for (var j = 0; j < validators.length; j++) {

                if (validators[j] == "Required") {

                    if (control.disabled == false && control.value == "") {
                        this.AddErrorMessage(control, Language.GetCode("Base.FieldRequired"));
                        return false;
                    }
                } else {
                    if (!eval(validators[j] + ".Verify(control, this)")) {
                        return false;
                    }
                }
            }

        } else
        {
            return true;
        }

        return true;
    };

    /**
     * Vérification des uploader
     * Si les fichiers sont obligatoire ou pas
     */
    this.VerifiyUpload = function (control) {

        var validators = control.getElementsByClassName("validators");
        var img = control.parentNode.getElementsByClassName("uplloadImage");
       
        //Suppression des message d'erreurs           
        this.RemoveErrorMessage(control);

        if (validators[0].value.indexOf("Required") > -1 && img.length == 0) {

            this.AddErrorMessage(control, Language.GetCode("Base.FieldRequired"));

            return false;
        } else {
            return true;
        }
    };

    /***
     * Ajout un message d'erreur en dessous du control
     * @returns {undefined}
     */
    this.AddErrorMessage = function (control, message) {

        var container = control.parentNode;

        var divError = document.createElement("div");
        divError.className = "errorControl";
        divError.innerHTML = message;

        container.appendChild(divError);
    };

    /***
     * Remove message Error
     * @param {type} control
     * @param {type} message
     * @returns {undefined}
     */
    this.RemoveErrorMessage = function (control) {

        var container = control.parentNode;
        var errorControl = container.getElementsByClassName("errorControl");

        if (errorControl.length > 0) {
             errorControl[0].parentNode.removeChild(errorControl[0]);
        }
    };

    /***
     * Y t'il d'autre erreur
     * @returns {undefined}
     */
    this.HaveError = function () {
        var currentForm = document.getElementById(this.formId);
        var errors = currentForm.getElementsByClassName("errorControl");
        return (errors.length == 0);
    };

    /***
     * Vérifie le contenu selon le type
     * @returns {undefined}
     */
    this.VerifyType = function (control) {

        //TODO RAJOUTER TOUS LES TYPE
        switch (control.type)
        {
            case "email" :
                return EmailBox.Verify(control.value);
                break;
        }

        return true;
    };

    /**
     * Serialize les controles remplies
     * Pas besoin de vérification cela a été fait avant
     * @param {*} formId 
     */
    this.Serialize = function (formId, prefix)
    {
        var data = "";

        if (prefix == undefined) {
            prefix = "";
        }

        currentForm = document.getElementById(formId);

        //Input standard
        var inputs = currentForm.getElementsByTagName("input");
        var textearea = currentForm.getElementsByTagName("textarea");

        for (var i = 0; i < inputs.length; i++)
        {
            if (inputs[i].type == "button")
            {
            } 
            else if (inputs[i].type == "checkbox")
            {
                if (inputs[i].checked == true) {
                    data += "&" + prefix + inputs[i].name + "=" + inputs[i].value;
                }
            } else if (inputs[i].type == "radio")
            {
                if (inputs[i].checked == true) {
                    data += "&" + prefix + inputs[i].name + "=" + inputs[i].value;
                }
            } else if (inputs[i].value != "")
            {
                data += "&" + prefix + inputs[i].name + "=" + inputs[i].value;
            }
        }

        for (var i = 0; i < textearea.length; i++)
        {
            if (textearea[i].value != "")
            {
                data += "&" + prefix + textearea[i].name + "=" + textearea[i].value;
            }
        }

        //Select
        var selects = currentForm.getElementsByTagName("select");

        for (var i = 0; i < selects.length; i++)
        {
            if(selects[i].multiple != undefined){
           
                let optionSelected = Array();
                let options = selects[i].getElementsByTagName("option");
                   
                   for(var j= 0; j < options.length; j++){
                    if(options[j].selected){
                        optionSelected.push(options[j].value);
                    }
                   }
                   
                data += "&" + prefix + selects[i].name + "=" + optionSelected.join(",");
            } else if (selects[i].value != ""){
                data += "&" + prefix + selects[i].name + "=" + selects[i].value;
            }
        }

        //upload
        var uploaderDiv = currentForm.getElementsByClassName("uploaderDiv");

        for (var i = 0; i < uploaderDiv.length; i++)
        {
            var imgs = Array();
            var uplloadImage = uploaderDiv[i].parentNode.getElementsByClassName("uplloadImage");

            for (var j = 0; j < uplloadImage.length; j++)
            {
                var img = uplloadImage[j].getElementsByTagName("img");

                for (var k = 0; k < img.length; k++)
                {
                    imgs.push(img[k].src);
                }
                
                var input = uplloadImage[j].getElementsByTagName("input");

                for (var k = 0; k < input.length; k++)
                {
                    imgs.push(input[k].value);
                }
            }
          
            data += "&" + prefix + uploaderDiv[i].id + "=" + imgs.join(",");
        }

        return data;
    };

    /**
     * Affiche un message d'erreur
     */
    this.RenderError = function (formId, message)
    {
        var form = document.getElementById(formId);
        error = form.getElementsByClassName("error");

        if(Array.isArray(message)){
            error[0].innerHTML = message.join('<br/>');
        } else{
            error[0].innerHTML = message;
        }
    };

    /***
     * Affiche un message de success
     * @param {type} formId
     * @param {type} message
     * @returns {undefined}
     */
    this.RenderSuccess = function (formId, message)
    {
        var form = document.getElementById(formId);
        error = form.getElementsByClassName("success");

        if(Array.isArray(message)){
            error[0].innerHTML = message.join('<br/>');
        } else{
            error[0].innerHTML = message;
        }
    };

    /***
     * Efface les messages d'information
     */
     this.CleanMessage = function(formId){
         this.RenderSuccess(formId, "");
         this.RenderError(formId, "");
     };
     
    /*
     * Obtient la valeur de l'id cace
     */
    this.GetId = function (formId)
    {
        var form = document.getElementById(formId);

        if (form != null) {
            hdId = form.querySelector("#Id");
            return hdId.value;
        }

        return "";
    };

    /*
     * Change la valeur du change Id caché
     * Afin de pouvoir faire un update apres un inser
     */
    this.SetId = function (formId, id) {
        var form = document.getElementById(formId);

        hdId = form.querySelector("#Id");
        hdId.value = id;
    };

    /*
     * Remet à jour les datasources ci besoin
     */
    this.SetDataSource = function (sourceName, data) {

        var hiddens = document.querySelectorAll("input[type=hidden]");

        for (var i = 0; i < hiddens.length; i++) {

            if (hiddens[i].dataset != null && hiddens[i].dataset.sourcename == sourceName) {
                hiddens[i].value = data;
            }
        }
    };

    /***
     * Récupére la valeur d'un champ
     * @param {type} formId
     * @param {type} inputId
     * @returns {unresolved}
     */
    this.GetValue = function (formId, inputId) {

        var form = document.getElementById(formId);
        var control = form[inputId];

        return control.value;
    };

    this.SetValue = function (formId, inputId, value) {

        var form = document.getElementById(formId);
        var control = form[inputId];

        return control.value = value;
    };
    /***
     * Supprime une image
     * @returns {undefined}
     */
    this.RemoveImage = function (control) {

        var container = control.parentNode;
        image = container.getElementsByTagName("img");

        Animation.Confirm(Language.GetCode("ConfirmDeleteImage"), () => {
            Request.Execute("DeleteImage", image[0].src);

            container.parentNode.removeChild(container);
        }
        );
    };

    /***
     * Affiche le loading
     */
    this.Loading = function (formId, show) {

        let form = Dom.GetById(formId);
        let succes = form.getElementsByClassName("success");

        if (show) {
            succes[0].innerHTML = "<img src= '" + location.origin + "/images/loading/load.gif' />";
        } else {
            succes[0].innerHTML = "";
        }
    };

     /**
     * Ajoute un validateur
     * @param {} controlId 
     * @param {*} validator 
     */
    this.AddValidator = function(controlId, validator){
        let control = Dom.GetById(controlId);
        control.dataset.validator = validator;
    };

    /***
     * Supprime une validateur
     */
    this.RemoveValidator = function(controlId, validator){
        let control = Dom.GetById(controlId);

        if(control.dataset != undefined){
            control.dataset.validator = undefined;
        }
    };
    
    /***
     * Vide tous les contrôles
     * @returns {undefined}
     */
    this.Reset = function(formId){
      
       let currentForm = document.getElementById(formId);

        //Input standard
        var inputs = currentForm.getElementsByTagName("input");
        var textearea = currentForm.getElementsByTagName("textarea");

        for (var i = 0; i < inputs.length; i++)
        {
            switch(inputs[i].type ) {
                case "checkbox":
                    inputs[i].checked = false;
                break; 
                case "button":
                break;
                default:
                   inputs[i].value = "";
                break;
            }
        }
        
        for (var i = 0; i < textearea.length; i++)
        {
            textearea[i].value = '';
        }
    };

}
;
