<!DOCTYPE html>
<html>

<!-- 
TO-DO LIST:
  * sanitize inputs to prevent CORS / XSS
-->

<head>
  <%- include("../partials/header.ejs") %>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
      integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.10.4/dayjs.min.js"></script>
    <script src="https://kit.fontawesome.com/c65a03b059.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/validator@13.5.2/validator.min.js"></script>
    <script>dayjs().format()</script>
</head>

<body>

  <%- include("../partials/nav.ejs") %>

    <div class="section" id="loginForm" style="padding-left: 10rem; padding-right: 10rem;">

      <div class="block" style="padding-left: 15rem; padding-right: 15rem;">
        <h1 class="title">Login</h1>
        <div class="box">
          <div class="field">
            <label class="label">Email</label>
            <div class="control has-icons-left">
              <input type="email" class="input" placeholder="Enter your account's email" id="userEmail">
              <span class="icon is-small is-left">
                <i class="fas fa-envelope"></i>
              </span>
            </div>
          </div>
          <div class="field">
            <label class="label">Password</label>
            <div class="control has-icons-left">
              <input type="password" class="input" placeholder="Enter your account's password" id="userPassword">
              <span class="icon is-small is-left">
                <i class="fas fa-lock"></i>
              </span>
            </div>
          </div>
        </div>
        <button id="loginButton" class="button is-dark" onclick="attemptAuth()">Login</button>
      </div>
    </div>
    </div>


    <script>
      function attemptAuth() {
        var redirectURL = "<%=redirectURL%>";
        console.log(redirectURL);
        $('.login-error').remove();
        let userEmail = $('#userEmail').val();
        let userPassword = $('#userPassword').val();

        let loginErrorHTML = '<article id="loginError" class="message is-danger is-normal login-error" style="margin-top: 2rem"> <div class="message-header"><p>Login Error</p></div><div class="message-body">The email or password you entered were incorrect!</div></article>';
        let emailConfirmationErrorHTML = '<article id="emailConfirmationError" class="message is-danger is-normal login-error" style="margin-top: 2rem"> <div class="message-header"><p>Please Confirm Your Email</p></div><div class="message-body">Please check your email for a confirmation link! If it does not show up immediately, please wait for a minute or two.</div></article>';
        let emailErrorHTML = '<article id="emailError" class="message is-warning is-normal login-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">The email you entered was invalid!</div></article>';
        let passwordErrorHTML = '<article id="passwordError" class="message is-warning is-normal login-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">The password you entered was not 6 characters long!</div></article>';
        let serverErrorHTML = '<article id="serverError" class="message is-danger is-normal login-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">An error occurred on our servers! Please wait a few minutes then try again. If the issue persists, please contact support.</div></article>';
        let unknownErrorHTML = '<article id="unknownError" class="message is-danger is-normal login-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">An unidentifiable error occurred! Please wait a few minutes then try again. If the issue persists, please contact support.</div></article>';
        let successHTML = '<article id="unknownError" class="message is-success is-normal" style="margin-top: 2rem"> <div class="message-header"><p>Auth Success</p></div><div class="message-body">Successfully logged in. Redirecting you now....</div></article>';

        if (!validator.isEmail(userEmail)) {
          $('#loginButton').after(emailErrorHTML);
        } else if (userPassword.length < 6) {
          $('#loginButton').after(passwordErrorHTML);
        }
        else {
          $('.login-error').remove();
          userEmail = validator.normalizeEmail(userEmail);
          $('#userEmail').replaceWith('<input type="email" class="input" placeholder="Enter your account\'s email" id="userEmail" disabled>');
          $('#userPassword').replaceWith('<input type="password" class="input" placeholder="Enter your account\'s password" id="userPassword" disabled>');

          let toPost = "/auth/login";
          var hi = new URLSearchParams(window.location.search);
          console.log(hi)
          if (!(hi.get("redirect") === null)){
            toPost += "?redirect="+ hi.get("redirect");
          }
          console.log(toPost);

          axios.post(toPost, {
            "email": userEmail,
            "password": userPassword
          }).then(response => {
            $('.login-error').remove();
            $('#loginButton').after(successHTML);
            window.location.replace(redirectURL);
          }).catch(error => {
            
            console.log(error.response);
            
            //enable email/pw input again
            $('#userEmail').replaceWith('<input type="email" class="input" placeholder="Enter your account\'s email" id="userEmail">');
            $('#userPassword').replaceWith('<input type="password" class="input" placeholder="Enter your account\'s password" id="userPassword">');

            //give error message
            if (error.response.status === 401 && error.response.data === 'Error: Invalid Email or Password') {
              $('#loginButton').after(loginErrorHTML);
            } else if (error.response.status === 403 && error.response.data === 'Error: Please confirm your email') {
              $('#loginButton').after(emailConfirmationErrorHTML);
            } else if (error.response.status === 501) {
              $('#loginButton').after(serverErrorHTML);
            } else {
              $('#loginButton').after(unknownErrorHTML);
            }
          });
        }


      }

      const sessionCookie = document.cookie;

    </script>

</body>
</html>