const session_url = "app/home/session.html";
  
$.ajaxSetup({
  cache: false,
  //headers: { "cache-control": "no-cache" }
});

/* Remove Cookie */
function delete_cookie(cname) {
  var expires = "expires=Thu, 01 Jan 1970 00:00:00 UTC;";
  document.cookie = cname + "=;" + expires + ";path=/";
}

/* Set Cookie */
function set_cookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

/* Get Cookie */
function get_cookie(cname) {
  var name = cname + "=";
  var decoded_cookie = decodeURIComponent(document.cookie);
  var ca = decoded_cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function is_empty(str) {
  return (!str || 0 === str.length);
}

function is_valid_user(response) {
  try {
    var user_data = response; /* JSON.parse( ) */
    var user_valid = user_data.valid_user;
    var users_id = parseInt(user_data.users_id);
    var user_rights = user_data.rights;
    if (users_id > 0 && user_valid === true) {
      return [users_id, true, user_rights];
    }
    return [0, false, user_rights];
  } catch (err) {
    console.error(err.message);
    return [0, false, false];
  }
}

var user = function (req, event, next) {
  if ($('#users-id').length) {
    /* This is the normal path for users logged in with top-bar session */
    debug_print("User is logged in as: " + $('#users-id').val());
    req.user = $('#users-id').val();
    next(); /* Call the next thing on the router */ 
  } else {
    /* This is an abnormal path. It's called when top-bar fails to work */
    var is_user_dfd = check_user({username: 'default', password: 'default'});
    $.when(is_user_dfd).done(function () {
       next(); /* Call the next thing on the router */  
    }).fail(function() {
       
    });
  } // end if user length
  
  $("#password").off('keypress');
  $("#password").on('keypress', function (event) {
    if (event.which === 13 || event.keyCode === 13 || event.key === "Enter") {
      var is_user_dfd = do_check_login(); // DO login when Enter Key press on Password field
      $.when(is_user_dfd).done(function () {
        next(); /* Call the next thing on the router */  
      }).fail(function() {

      });
    }
  });

  $("#loginSubmit").off('click');
  // Row click function for Tenant Profile
  $("#loginSubmit").on("click", function () {
    var is_user_dfd = do_check_login(); // DO login when Enter Key press on Password field
      $.when(is_user_dfd).done(function () {
        next(); /* Call the next thing on the router */  
      }).fail(function() {

      });
  });

  function do_check_login() {
    $("#loginError").css('display', 'none');
    var user = $("#username").val();
    var pass = $("#password").val();

    if (!is_empty(user) && !is_empty(pass)) {
      delete_cookie('scrollPos');
      var auth_obj = {username: user, password: pass};
      return check_user(auth_obj);
    }

    setTimeout(function () {
      $("#loginError").css('display', 'inline-block');
    }, 500);
  }

  function check_user(auth_obj) {
      var dfd = jQuery.Deferred();
//    var result = get_json_data(auth_obj, session_url);
//    result.then(function (response) {
      $.ajax({ 
          type: "POST", 
          url: session_url, 
          dataType: 'json', 
          async: true, 
          contentType: 'application/json',
          data: JSON.stringify(auth_obj),
          success: function(response) {
              
      var ret = is_valid_user(response);
      var users_id = ret[0];
      var valid = ret[1];
      var rights = ret[2];
      if (rights === false) {
        var is_attack = -1;
      } else {
        var is_attack = rights.indexOf("attack");
      }
      if (valid === false) {
        if (is_attack === -1) {
          $('#login-prompt-box')
                  .modal('setting', 'closable', false)
                  .modal('show');
          if (auth_obj.username !== 'default') {
            $('#loginError').text('Invalid Username or Password.');
          }
        } else {
          $('#login-prompt-box')
                  .modal('setting', 'closable', false)
                  .modal('show');
          $('#loginError').text('Account Locked - bad attempts. Please wait 20 seconds, before logging in!');
        }
      } else if (valid === true) {
        req.user = users_id;
        
        $("#loginError").css('display', 'none');
        $('#login-prompt-box').modal('hide');
//            $.get( "app/home/get_full_name.html", function( data ) {
//              $( "#fullName" ).html( data ); /* Show users name in profile display */
//            }); 
        /* This is needed by varrious forms, Do NOT remove, please */
        $('<input>').attr({type: 'hidden', id: 'users-id', name: 'users_id', value: req.user}).appendTo('body');
        dfd.resolve(true); // Logged in
      } else {
        console.log('System session was odd.');
        dfd.reject(false);
      }
//    }).catch(function (error) {
//      throw "Session Error";
//    });
          }
      });
      return dfd.promise();
  }; // End of check_user
  
}; // End of user

function show_loader(req, event, next) {
  // Hide Clock / Show Loader
  $('#clock').css('display', 'none'),
  $('#topLoad').css('display', 'inline-block');
  // Show left loading spinner
  $("#main-container-left-body").addClass("loading");
  $("#main-container-right-body").addClass("loading");
  next();
}