<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Login</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"
    />
    <script
      src="https://code.jquery.com/jquery-3.5.1.js"
      integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
      crossorigin="anonymous"
    ></script>
    <link rel="stylesheet" href="/public/login.css" type="text/css" />
  </head>

  <body class="image">
    <div class="container-fill h-100">
      <div class="row justify-content-center h-100">
        <div class="float-right col-12 col-sm-6 col-md-3 color h-100">
          <form class="form-container h-100 margin">
            <div class="form-group">
              <h3>Login</h3>
            </div>
            <div class="form-group">
              <label for="username">Username</label>
              <input
                type="text"
                class="form-control"
                placeholder="Username"
                name="username"
                id="username"
              />
              <p id="regusername">Invalid username</p>
              </div>
            <div class="form-group">
              <label for="password">Password</label>
              <input
                type="password"
                class="form-control"
                placeholder="********"
                name="password"
                id="password"
              />
              </div>
              <div class="form-group">
              <button class="btn btn-primary btn-block">Login</button>
            </div>
          </form>
          <div class="createlink">
            <a href="/create">Create an account</a>
          </div>
        </div>
      </div>
    </div>

    <script>
      $("form").submit((e) => {
        e.preventDefault();
        let bool = true;
        const userregex = /^[A-Za-z0-9_]{3,20}$/;
        const passwordregex = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;

        
        if (!$("#username").val().match(userregex)) {
          bool = false;
          $("#regusername").css("display", "block");
        }

        if (bool) {
          let values = {};
          $.each($("form").serializeArray(), function (i, field) {
            values[field.name] = field.value;
          });
          $.ajax({
            type: "POST",
            url: "/login",
            data: values,
            success: (data) => {
              if(data.check === true){
                  window.location = "http://localhost:3030/";
              }
              else{
                alert("Invalid credentials")
              }
            },
          });
        }
      });
    </script>
  </body>
</html>