var AlertPlugin = function () {};

/***
 * Init the plugin
 * @returns {undefined}
 */
AlertPlugin.Init = function (formToSave = "") {
    Event.AddById("btnCreateAlert", "click", AlertPlugin.CreateAlert);
    AlertPlugin.FormToSave = formToSave;
};

AlertPlugin.InitFront = function (formToSave = "") {
    Event.AddByClass("iconCreateAlert", "click", AlertPlugin.ShowCreateAlert);
    AlertPlugin.FormToSave = formToSave;
};

/***
 * Add Alert to a entity
 */
AlertPlugin.CreateAlert = function () {

    if (Form.IsValid("alertForm")) {

        Animation.AddLoading("alertForm");
        Animation.Hide("alertForm");

        Plugin.SendRequest({"plugin": "AlertPlugin",
            "method": "CreateAlert",
            "Data": btoa(Form.Serialize(AlertPlugin.FormToSave)),
            "EntityName": "AnnonceFilter",
            "EntityId": "",
            "Email": Form.GetValue("alertForm" , "Email"),
            "FirstName": Form.GetValue("alertForm" , "FirstName"),
            "Name": Form.GetValue("alertForm" , "Name"),

        }
        , (data) => {
      
            Animation.RemoveLoading("alertForm");
            Animation.Show("alertForm");
            Animation.Load("alertForm", data);
         });
    }
};

/***
 * Dialo d'ajout d'alerte
 */
AlertPlugin.ShowCreateAlert = function(e){
    console.log("Show Create Alerte");
    let element = e.srcElement;

    Dialog.open('', {"title": e.srcElement.title,
        "html": "<div id='AlertPluginDialog'></div>",
    });

    AlertPlugin.entityName = e.srcElement.dataset.entityname;
    AlertPlugin.entityId = e.srcElement.dataset.entityid;;

    Plugin.SendRequest({"plugin": "AlertPlugin",
        "method": "RenderAlertForm",
    }
    , (data) => {
        Animation.Load("AlertPluginDialog", data);

        Dialog.Reposition();

        Event.AddById("btnCreateAlert", "click", AlertPlugin.SendAlertForm);

    });

    AlertPlugin.SendAlertForm = function () {

        if (Form.IsValid("alertForm")) {
            Animation.AddLoading("alertForm");
            Animation.Hide("alertForm");

            Plugin.SendRequest({"plugin": "AlertPlugin",
                "method": "CreateAlert",
                "Email": Form.GetValue("alertForm", "Email"),
                "FirstName": Form.GetValue("alertForm", "FirstName"),
                "Name": Form.GetValue("alertForm", "Name"),
                "EntityName": AlertPlugin.entityName,
                "EntityId": AlertPlugin.entityId
            }
            , (data) => {
                Animation.RemoveLoading("alertForm");
                Animation.Load("alertForm", data);
                Animation.Show("alertForm");
            });
          }
    };
};