/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
En cas de mofification des options => mettre à jour la doc du wiki gitlab
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
var ajaxget = function(url) {
  $.ajax({
    url: `https://api.maildigit.fr/template/${url}.mustache`,
    datatype: "jsonp",
    success: function(tplq) {
      logger.info(tplq);
      logger.info(quest);
      return Mustache.render(tplq, quest);
    }
  });
};
$(document).ready(function() {
  /*
  Cette partie sera généré dans les sections et il ne restera
  que $('.formmanager form').gestionform()

  */
  //  $(".formmanager").each(function(i) {
  document.querySelectorAll("div.formmanager").forEach(form => {
    //let bloc = $(this).attr("id");
    let bloc = form.getAttribute("id");
    axios.get(`./${bloc}.json`).then(function(rep) {
      // recup les templatemp
      logger.info("rep     ddddd", rep);
      let tpl = [rep.data.info.tpl];
      $.each(rep.data.quest, function(q, quest) {
        logger.info(quest);
        if (tpl.indexOf(quest.tpl) == -1) {
          tpl.push(quest.tpl);
        }
        logger.info("template", tpl);
      });
    });
  });
});
  /*
      //https://api.maildigit.fr/template/
      $.get(data.info.tpl, function(tpl) {
        let questhtml = $.map(data.quest, function(quest, q) {
          logger.info(q);
          logger.info(quest);
          quest.idhtml = data.info.idhtml;
          $.ajax({
            url: data.quest[q].tpl,
            datatype: "jsonp",
            async: false,
            success: function(tplq) {
              logger.info(tplq);
              logger.info(quest);
              return Mustache.render(tplq, quest);
            }
          });
        });
        logger.info(questhtml);
        data.content = questhtml.join(" ");
        logger.info(data);
        let fullform = Mustache.to_html(tpl, data);
        $(data.info.idhtml).html(fullform);
        $(".formmanager form").gestionform();
      });
    });
  });
});*/

  function($) {
    $.fn.gestionform = function() {
      let form = $(this);
      var lastdatasend = lastdatasend || "";
      form.find("input").keyup(function(e) {
        if (e.which == 13) {
          form.find(".btnSendForm").click();
        }
      });
      form.find("select").on("click", function() {
        let chph = $(this).data("hiddenchamps");
        var valh = $(this)
          .find("option:selected")
          .text();
        form.find("input[data-champs='" + chph + "']").val(valh);
      });
      form.find(".type-choix button").on("click", function() {
        var blocchoix = $(this).closest(".type-choix");
        blocchoix.find("button").removeClass("active");
        $(this).addClass("active");
        form
          .find("input[data-champs='" + blocchoix.data("champs") + "']")
          .val($(this).data("val"));
      });
      form.find(".type-multichoix button").on("click", function(e) {
        e.preventDefault();
        var reponsemultiple = [];
        var blocmultichoix = $(this).closest(".type-multichoix");
        var champsdest = blocmultichoix.attr("data-champs");
        logger.info(champsdest);
        var nbmaxchoix = parseInt(blocmultichoix.attr("data-nbmaxchoix"));
        $(this).toggleClass("active");
        if ($(".type-multichoix button.active").length > nbmaxchoix) {
          alert("Choisissez au maximum " + nbmaxchoix + " choix!");
          $(this).toggleClass("active");
        } else {
          blocmultichoix.find("button.active").each(function(i) {
            reponsemultiple.push($(this).attr("data-choix"));
          });
          blocmultichoix
            .find("input[data-champs='" + champsdest + "']")
            .val(JSON.stringify(reponsemultiple));
        }
      });
      form.find(".btnSendForm").on("click", function(e) {
        e.preventDefault();
        var formencours = $(this).closest("form");
        var r = localStorage.getItem("r");
        if (r == undefined) {
          r = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
            c
          ) {
            var r = (Math.random() * 16) | 0,
              v = c == "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
          });
          localStorage.setItem("r", r);
        }
        var senddata = { r: r };
        var etat = "";
        var msgok = formencours.data("msgok");
        var msgko = formencours.data("msgko");
        formencours.find("textarea").each(function() {
          senddata[$(this).data("champs")] = $(this).val();
          if ($(this).val() == "" && $(this).data("check") == "notnull") {
            etat += $(this).data("msgerreur") + "<br>";
          }
        });
        formencours.find(".blochtml").each(function() {
          senddata[$(this).data("champs")] = $(this).html();
        });
        formencours.find("input").each(function(i) {
          senddata[$(this).data("champs")] = $(this).val();
          var reg = "{{" + $(this).data("champs") + "}}";
          msgok = msgok.replace(reg, $(this).val());
          msgko = msgko.replace(reg, $(this).val());

          if ($(this).data("check") == "email") {
            /*
           var reg = new RegExp(
            '^[a-z0-9]+([_|.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|.|-]{1}[a-z0-9]+)*[.]{1}[a-z]{2,6}$',
            'i'
          );
          var reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
          */
            var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

            //logger.info($(this).val());
            //logger.info(reg.test($(this).val()) );
            if (!reg.test($(this).val())) {
              if (!$(this).data("msgerreur")) {
                etat += "invalid email";
              } else {
                etat += $(this).data("msgerreur") + "<br>";
              }
            }
          }
          if ($(this).data("check") == "phone") {
            var phone = $(this)
              .val()
              .replace("+33", "0")
              .replace(/[^0-9]/g, "");
            if (phone.length != 10) {
              if (!$(this).data("msgerreur")) {
                etat += "invalid phone";
              } else {
                etat += $(this).data("msgerreur") + "<br>";
              }
            }
          }
          if ($(this).data("check") == "notnull") {
            if ($(this).val() == "") {
              if (!$(this).data("msgerreur")) {
                etat += "empty field";
              } else {
                etat += $(this).data("msgerreur") + "<br>";
              }
            }
          }
          if ($(this).data("check") == "valpositif") {
            if (parseInt($(this).val()) < 0) {
              if (!$(this).data("msgerreur")) {
                etat += "invalid value have to be positive";
              } else {
                etat += "valpos " + $(this).data("msgerreur") + "<br>";
              }
            }
          }
          if ($(this).data("check") == "codepostal") {
            if ($(this).val().length != 5) {
              if (!$(this).data("msgerreur")) {
                etat += "invalid zipcode";
              } else {
                etat += "cp" + $(this).data("msgerreur") + "<br>";
              }
            }
          }
          if ($(this).data("check") == "departement") {
            var dep = 0;
            if ($.isNumeric($(this).val())) {
              dep = parseInt($(this).val());
            }
            if (!(dep > 0 && dep < 96)) {
              if (!$(this).data("msgerreur")) {
                etat += "invalid french departement";
              } else {
                etat += "dep " + $(this).data("msgerreur") + "<br>";
              }
            }
          }
        });
        logger.info(JSON.stringify(senddata));
        var diff = false;
        if (lastdatasend == "") {
          diff = true;
        }
        $.each(lastdatasend, function(k, v) {
          if (k in senddata && v != senddata[k]) {
            diff = true;
          }
        });
        if (!diff) {
          etat =
            "Action déjà effectuée, si vous recliquez, vous allez renvoyer la même demande";
          lastdatasend = "";
        }
        logger.info(etat);
        if (etat != "") {
          formencours.find("p.msgform").html(etat);
        } else {
          logger.info(
            "https://api.maildigit.fr" + formencours.data("formmaildigit")
          );
          logger.info(
            formencours.data("tribeid") +
              "_" +
              $("html").attr("lang") +
              "_" +
              formencours.data("auth") +
              "_" +
              formencours.data("uuid")
          );
          $.ajax({
            url: "https://api.maildigit.fr" + formencours.data("formmaildigit"),
            type: "POST",
            beforeSend: function(request) {
              request.setRequestHeader(
                "x-Client-id",
                formencours.data("tribeid")
              );
              request.setRequestHeader("x-language", $("html").attr("lang"));
              request.setRequestHeader("x-auth", formencours.data("auth"));
              request.setRequestHeader("x-uuid", formencours.data("uuid"));
            },
            data: senddata,
            cache: false,
            success: function(res) {
              //logger.info(e);
              var app = app || {};
              lastdatasend = senddata;
              logger.info(formencours.data("msgok"));
              logger.info(res);
              if (res.idpanier) {
                $("button.clickvalidecommande").data("idpanier", res.idpanier);
                logger.info("trig clickvalidecommande via form");
                $("button.clickvalidecommande").trigger("click");
              }
              formencours.find("p.msgform").html(msgok);
              //var chargeext = app.custom(senddata) || 'Pas de custom à executer';
            },
            error: function(e) {
              logger.info(e);
              //formencours.data(state).val('error');
              formencours.find("p.msgform").html(msgko);
            }
          });
        }
      });
    };
    $.fn.functionname = function(contenu) {};
  }
)(jQuery);
