var MessageForm = function(){};

/***
 * Initialise le formulaire
 * @returns {undefined}
 */
MessageForm.Init = function(callBack){
    Event.AddById("btnSaveMessage", "click", MessageForm.SaveElement);
    MessageForm.callBack = callBack;
    
    EntityGrid.Initialise('gdReponse');
    
     let txtEditor = new TextRichEditor(document.querySelector("#MessageFormForm #Message"), 
              {tools: ["SourceCode"]}
            );
};

/***
* Obtient l'id de l'itin�raire courant 
*/
MessageForm.GetId = function(){
    return Form.GetId("MessageFormForm");
};

/*
* Sauvegare l'itineraire
*/
MessageForm.SaveElement = function(e){
   
    if(Form.IsValid("MessageFormForm"))
    {

    var data = "Class=Forum&Methode=UpdateMessage&App=Forum";
        data +=  Form.Serialize("MessageFormForm");

        Request.Post("Ajax.php", data).then(data => {

            data = JSON.parse(data);

            if(data.statut == "Error"){
                Form.RenderError("MessageFormForm", data.message);
            } else{

                 Dialog.Close();
                
                if(MessageForm.callBack){
                    MessageForm.callBack(data);
                }
            }
        });
    }
};

/***
 * Delete a reponse
 * @returns {undefined}
 */
MessageForm.DeleteReponse = function(id, params, control){

    let container = control.parentNode.parentNode;

    Animation.Confirm(Language.GetCode("Forum.ConfirmRemoveResponse"), function(){

     let data = "Class=Forum&Methode=DeleteReponse&App=Forum";
         data += "&reponseId=" + id;

        Request.Post("Ajax.php", data).then(data => {
            container.parentNode.removeChild(container);
        });
    });
};

/***
 * Delete a reponse
 * @returns {undefined}
 */
MessageForm.EditReponse = function(id, params, control){
    
    let container = control.parentNode.parentNode;
    let messageContainer = container.getElementsByTagName("td")[1];
    let txtEditor = new TextRichEditor(messageContainer.getElementsByTagName("div")[0],
            {tools: ["SaveContent" ,"SourceCode"],
                events: [{"tool": "SaveContent", "events": [{"type": "mousedown", "handler": updateReponseContent}]}],
            }
    );
    
    function updateReponseContent(){
        let data = "Class=Forum&Methode=UpdateReponse&App=Forum";
        data += "&reponseId=" + id;
        data += "&reponse="+ txtEditor.getContent();

        Request.Post("Ajax.php", data).then(data => {

            txtEditor.quit();
        });
    }
    
};
