<script lang="ts">
  import type {CognitoUser} from "amazon-cognito-identity-js";

  import { forgotPassword, forgotPasswordSubmit, signIn } from "../clients/amplify";  
  import authStore from "../stores/auth";
  import Modal from "../components/Modal.svelte";

  let user: CognitoUser | null = null;
  let username = "";
  let password = "";
  let newPassword = "";
  let newPasswordRepeat = "";
  let resetCode = "";
  let settingNewPassword = false;
  let resettingPassword = false;
  let error = null;
  let done = false;

  function startPasswordReset() {
    forgotPassword(username).then(() => {
      settingNewPassword = true;
      resettingPassword = true;
    }).catch(err => {
      error = "Reset request failed: " + err.message;
    })
  }

  function login() {
    error = null;

    if (settingNewPassword) {
      if (newPasswordRepeat !== newPassword) {
        error = "New passwords do not match.";
        return;
      }

      if (resettingPassword) {
        forgotPasswordSubmit(username, resetCode, newPassword).then(() => {
          authStore.check();
          settingNewPassword = false;
          resettingPassword = false;
        }).catch(err => {
          error = "Reset submit failed: " + err.message;
        });
      } else {  
        user.completeNewPasswordChallenge(newPassword, null, {
          onSuccess: () => {
            done = true;
            authStore.check();
          },
          onFailure: err => {
            error = err
          },
        })
      }
    } else {
      signIn(username, password).then(newUser => {
        if (!newUser) {
          error = "Incorrect username or password."
          return
        }

        if ((newUser as any).challengeName === "NEW_PASSWORD_REQUIRED") {
          error = "Password is expired, please update it."
          settingNewPassword = true;
        } else {
          authStore.check();
          done = true;
        }

        user = newUser;
      }).catch(err => {
        error = err.message
      });
    }
  }
</script>

<Modal show={!done} title="Login" error={error}>
  <form on:submit|preventDefault={login}>
    <label for="username">Username</label>
    <input name="username" type="text" bind:value={username} />
    {#if !resettingPassword}
      <label for="password">Password</label>
      <input name="password" type="password" bind:value={password} />
    {:else}
      <label for="resetCode">Code From Email</label>
      <input name="resetCode" type="text" bind:value={resetCode} />
    {/if}
    {#if settingNewPassword}
      <label for="newPassword">New Password</label>
      <input name="newPassword" type="password" bind:value={newPassword} />
      <label for="newPasswordRepeat">Repeat Password</label>
      <input name="newPasswordRepeat" type="password" bind:value={newPasswordRepeat} />
    {/if}

    <hr />
    <button type="submit">Login</button>
    {#if !settingNewPassword}
      <button disabled={username === ""} on:click|preventDefault={startPasswordReset}>Forgot Password</button>
    {/if}
  </form>
</Modal>