var CardWidget = function(){};

/***
 * Initialise le formulaire
 * @returns {undefined}
 */
CardWidget.Init = function(){
    Event.AddById("shopCard", "click", CardWidget.OpenCart);
};

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

/***
 * Init Add To Card Button
 */
CardWidget.InitAddToCart = function(){

    Event.AddById("btnAddToCart", "click", CardWidget.AddToCart);
    Event.AddByClass("btnAddChildToCart", "click", CardWidget.AddChildToCart);
};

/***
 * Add Element on the Card
 */
CardWidget.AddToCart = function(){
    let idEntite = Form.GetId("CardWidgetForm");
    let data = "Class=Shop&Methode=AddToCart&App=Shop";
        data += "&entityId=" + idEntite;
    
    Request.Post("Ajax.php", data).then(data => {
     
        Animation.Notify(Language.GetCode("Shop.ProductAddedToCart"));

        CardWidget.UpdateCart(data);
    });
};

/***
 * Add Child Element on the Card
 */
CardWidget.AddChildToCart = function(e){

    let element = e.srcElement;

    while(element.className.indexOf("btnAddChildToCart") < 0 ){
        element = element.parentNode;
    }

    let idEntite = element.id;
    let data = "Class=Shop&Methode=AddToCart&App=Shop";
        data += "&entityId=" + idEntite;
    
    Request.Post("Ajax.php", data).then(data => {
     
        Animation.Notify(Language.GetCode("Shop.ProductAddedToCart"));

        CardWidget.UpdateCart(data);
    });
};

/*
* Ouvre/Ferme le mini panier
*/
CardWidget.OpenCart = function(e){
    let cartMenu = new ContextMenu(e);
        cartMenu.App = "Shop";
        cartMenu.Methode = "GetCart";
        cartMenu.Params = "";
        cartMenu.CssClass = "cartMenu";
        cartMenu.Width  = "450px";


        cartMenu.onLoaded = () => {
             Event.AddByClass("removeCartLine", "click" , CardWidget.RemoveLine );
        };
        cartMenu.Show();
};

/*
* Met à jour le panier  
*/
CardWidget.UpdateCart = function(data){
    let nbCart = Dom.GetById("nbCart");
    nbCart.innerHTML = data;
 };
 
 /***
  * Supprime un produit 
  * @param {type} e
  * @returns {undefined}
  */
 CardWidget.RemoveLine = function (e) {
 
     Animation.Confirm(Language.GetCode("Shop.RemoveProduct"), function () {
 
         let element = e.srcElement;

         console.log(element);
 
         let data = "Class=Shop&Methode=RemoveToCart&App=Shop";
         data += "&IdEntite=" + element.id;
 
         Request.Post("Ajax.php", data).then(data => {
 
             container = element.parentNode.parentNode.parentNode;
             container.removeChild(element.parentNode.parentNode);
 
             CardWidget.UpdateCart(data);
         });
     });
 };
