(function($) {
  const ROOT_TAAPP_URL = 'http://taapp.ndda.fr:3010';
  const ROOT_URL = 'http://maildigit.ndda.fr'

   $.fn.initlogin = function(URLCENTRALE) {
     function register(blocauth) {
       blocauth.html($('#register').html()).promise().done(function(){

         $('a.oubliemdp').on('click', function(e){e.preventDefault(); forget(blocauth)});
         $('a.login').on('click', function(e){e.preventDefault(); login(blocauth)});
         $('.register-button').on('click',function(e){
            e.preventDefault();
             var etat = "";
             var senddata = {'action':'register'};
             var reg = new RegExp('^[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');
             if (! reg.test($('#reg_email').val()) ) {
                etat += $('#reg_email').data('msgko') +"<br>";
              }else{
                senddata['email'] = $('#reg_email').val();
              };
             if ($('#reg_password').val() != $('#reg_password_confirm') && $('#reg_password').val().length < 5 ) {
               etat+=$('#reg_password').data('msgko') + "<br>";
             }else{
               senddata['psw'] = $('#reg_password').val();
             };
             if ( $('#reg_prenom').val().length < 3 ) {
                etat += $('#reg_prenom').data('msgko') +"<br>";
              }else{
                senddata['prenom'] = $('#reg_prenom').val();
              };
              if (  $('#reg_nom').val().length < 3 ) {
                 etat += $('#reg_nom').data('msgko') +"<br>";
               }else{
                 senddata['nom'] = $('#reg_nom').val();
               };
             senddata['genre'] = $("input[name='reg_gender']:checked").attr('id');
             if (!($('#reg_agree').is(':checked'))) {
               etat+=$('#reg_agree').data('msgko')+"<br>";
             };

             if (etat != "") {
               $('#register-form p.msgreg').html(etat);
             }else{
               $.ajax({ url: "/log", type: "POST", data:senddata, cache: false,
                     success: function(e) {
                        e=JSON.parse(e);
                        logger.info(e);
                        if (e.etat == "ok") {
                          login(blocauth);
                        }else{
                          logger.info(e.etat);
                        $('#register-form p.msgreg').html(e.etat);
                        };
                     },
                     error: function(e) {
                         logger.info(e);
                         $('#register-form p.msgreg').html($('#register-form').data('msgko'));
                     },
               });
             };
         });
       });
     };

     function directorySelector(blocauth) {
       blocauth.html($('.choose-directory').html()).promise().done(function () {
         $('.choose-directory__submit').on('click', function(e) {
           const selectedDirectory = $('.directory-selector option:selected').val();
           $.ajax({
             url: `${ROOT_TAAPP_URL}/nas/need-data/${selectedDirectory}`,
             type: "POST",
             beforeSend: function(request) {
               request.setRequestHeader('x-auth', localStorage.getItem('token'))
             },
             data: { login: 'max' },
             cache: false,
             success: function (data, textStatus, request) {
               logger.info('URL Node-File-Manager here!');
               logger.info('data: ', data);
               displayIframe(blocauth, data.url);
             },
             error: function (response) {
               logger.info('err: ', response);
             },
             always: function (response) {
               logger.info('Hello!')
             }
           });
         });
       });
     }

     function displayIframe(blocauth, url) {
       blocauth.html(`<iframe height="600" width="800" src=${url}> </iframe>`).promise().done(function() {
         logger.info('displayIframe');
       })
     }

    function login(blocauth) {
      blocauth.html($('#proclogin').html()).promise().done(function() {
          $('a.oubliemdp').on('click', function(e) {
            e.preventDefault();
            forget(blocauth);
          });
          $('a.register').on('click', function(e) {
            e.preventDefault();
            register(blocauth);
          });
          $('button.login-button').on('click', function(e) {
            e.preventDefault();
            const ROOT_URL = 'http://maildigit.ndda.fr'
            const tribeid = $(this).attr('data-tribeid');
            const $form = $('#login-form');
            const inputs = $form.serializeArray();
            let loginData = {};
            loginData.tribeid = tribeid;

            inputs.forEach(input => {
              if (input.value.trim().length > 0) {
                loginData[input.name] = input.value.trim();
              }
            });
            // Si les champs sont bien remplis on envoie la requête
            if (Object.keys(loginData).length === 3) {
              $.ajax({
                url: `${ROOT_URL}/login`,
                type: "POST",
                data: loginData,
                cache: false,
                success: function (data, textStatus, request) {
                  const token = request.getResponseHeader('x-auth');
                  logger.info('token: ', token);
                  localStorage.setItem('token', token);
                  directorySelector(blocauth);
                },
                error: function (response) {
                  logger.info('err: ', response.responseJSON.error);
                }
              });
            }
          });
        });
    }

     function forget(blocauth){
       blocauth.html($('#forgotpw').html()).promise().done(function(){
         $('a.login').on('click', function(e){e.preventDefault(); login(blocauth)});
         $('a.register').on('click', function(e){e.preventDefault(); register(blocauth)});

       });
     };

     login($(this));
   };

   $.fn.login = function(){
     var form = $(this);
     var lastdatasend = lastdatasend || "";
     form.find('.btnsendform').on('click',function(){
        var senddata = {};
        var etat = "";
        var msgok = form.data('msgok');
        var msgko = form.data('msgko');

        senddata.fichier = form.data('fichier');

        form.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');
            if (! reg.test($(this).val()) ) { etat += $(this).data('msgerreur') +"<br>";};
          };

          if ( $(this).data('check') == 'phone') {
            var phone = $(this).val().replace(/[^0-9]/g, '');
            if (phone.length != 10) {etat += $(this).data('msgerreur') +"<br>";};
          };

        });
        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";
        }
        if (etat != "") {
            form.find("p.msgform").html(etat);
        }else{
            $.ajax({ url: "http://maildigit.ndda.fr:3000/msg", type: "POST", data:senddata, cache: false,
                  success: function(e) {
                      //logger.info(e);
                      lastdatasend = senddata;
                      logger.info(form.data('msgok'));
                      form.find("p.msgform").html(msgok);
                  },
                  error: function(e) {
                      logger.info(e);
                      form.find("p.msgform").html(msgko);
                  },
            });
        };
     });
   };
   $.fn.functionname = function(contenu){
   };
}(jQuery));
