<html>

<head>
  <title>Blink - Sign In</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous">
  </script>
</head>

<style>
  .divider:after,
  .divider:before {
    content: "";
    flex: 1;
    height: 1px;
    background: #eee;
  }

  .h-custom {
    height: calc(100% - 73px);
  }

  @media (max-width: 450px) {
    .h-custom {
      height: 100%;
    }
  }
</style>

<body>

  <noscript>
    <div class="alert alert-danger" role="alert">
      This website will not work without JavaScript. Please enable JavaScript if you wish to continue using this website
    </div>
  </noscript>
  <div class="alert alert-danger" id="hiddenAlertMessage" role="alert" style="display: none;"></div>

  <section class="vh-100">
    <div class="container-fluid h-custom">
      <div class="row d-flex justify-content-center align-items-center h-100">
        <div class="col-md-9 col-lg-6 col-xl-5">
          <img id="image" class="img-fluid">
        </div>
        <div class="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
          <form>

            <div class="divider d-flex align-items-center my-4">
              <p class="text-center fw-bold mx-3 mb-0">Sign In</p>
            </div>

            <!-- Email input -->
            <div class="form-outline mb-4">
              <input type="email" id="email" class="form-control form-control-lg"
                placeholder="Enter your email address" onblur="emailFieldLosesFocus();" />
              <div class="invalid-feedback">
                Please enter an email address
              </div>
            </div>

            <!-- Password input -->
            <div class="form-outline mb-3">
              <input type="password" id="password" class="form-control form-control-lg" placeholder="Enter password"
                onblur="passwordFieldLosesFocus();" />
              <div class="invalid-feedback">
                Please enter your password
              </div>
            </div>

            <div class="d-flex justify-content-between align-items-center">
              <!-- Checkbox -->
              <div class="form-check mb-0">
                <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" />
                <label class="form-check-label" for="form2Example3">
                  Remember me
                </label>
              </div>
              <a href="forgot-password.html" class="text-body">Forgot password?</a>
            </div>

            <div class="text-center text-lg-start mt-4 pt-2">
              <button type="button" onclick="login()" class="btn btn-primary btn-lg"
                style="padding-left: 2.5rem; padding-right: 2.5rem;">Login</button>
              <p class="small mt-2 pt-1 mb-0">Don't have an account? <a class="link-primary text-decoration-none" href="register.html">Register</a></p>
            </div>
          </form>
        </div>
      </div>
    </div>
  </section>

  <script src="../js/constants.js"></script>
  <script src="../js/utils.js"></script>
  <script>
    window.onload = function () {
      loadImage();
    }

    /*
     * This function is responsible for the log-in process
     */
    async function login() {
      if (!validateFields()) {
        return;
      }
      const email = document.getElementById("email").value;
      const password = document.getElementById("password").value;


      const response = await fetch(`${API_URL}/persons/me/token`, {
        method: "POST",
        body: JSON.stringify({
          email: email,
          password: password
        }),
        headers: createHeaders(null)
      });
      const data = await response.json();

      if (response.ok) {
        document.cookie = `token=${data.token};`;
        window.location.href = 'userprofile.html?id=me';
      } else {
        showError(data.error);
        //callbackErrors(data.errors, showError);
      }
    }

    /*
     * Validate the field before the submit. This helps to prevent useless API
     * calls. Retrurns true or false
    */
    function validateFields(){
      const emailField = document.getElementById("email");
      const passwordField = document.getElementById("password");
      var isFormValid = true;

      if(!emailField.value || !validateEmail(emailField.value)){
        emailField.classList.add("is-invalid");
        isFormValid = false;
      }
      else{
        emailField.classList.remove("is-invalid");
      }

      if(!passwordField.value){
        passwordField.classList.add("is-invalid");
        isFormValid = false;
      }
      else{
        passwordField.classList.remove("is-invalid");
      }
      return isFormValid;
    }

    /*
     * This function is responsible for loading a random stock photo seen on the
     * left side of the page
     */
    function loadImage() {
      const random = Math.floor(Math.random() * 4);
      if (random == 0) {
        document.getElementById('image').src = '../content/stock_photo_1.png';
      } else if (random == 1) {
        document.getElementById('image').src = '../content/stock_photo_2.png';
      } else if (random == 2) {
        document.getElementById('image').src = '../content/stock_photo_3.png';
      } else if (random == 3) {
        document.getElementById('image').src = '../content/stock_photo_4.png';
      }
    }

    /*
     * This function gets called when the e-mail field loses focus. This is
     * done to inform the user whether the entered e-mail is in a valid format
     */
    function emailFieldLosesFocus() {
      const emailField = document.getElementById("email");
      if (!emailField.value || !validateEmail(emailField.value)) {
        emailField.classList.add("is-invalid");
      } else {
        emailField.classList.remove("is-invalid");
      }
    }

    /*
     * This function gets called when the password field loses focus. This is
     * done to inform the user that they are required to enter a password
     */
    function passwordFieldLosesFocus() {
      const passwordField = document.getElementById("password");
      if (!passwordField.value) {
        passwordField.classList.add("is-invalid");
      } else {
        passwordField.classList.remove("is-invalid");
      }
    }

    /*
     * This function shows an error using a Bootstrap's alert element
     */
    function showError(message) {
      const alertDiv = document.getElementById('hiddenAlertMessage');
      alertDiv.innerHTML = message;
      alertDiv.style.display = 'block';
    }
  </script>

</body>

</html>