<script>
  import Theme from "../../components/theme";
  import HoveringContentBox from "../../components/HoveringContentBox.svelte";
  import Api from "./api.ts";
  import Credentials from "./Credentials.svelte";
  import Redirect from "./Redirect.svelte";
  import Twofactor from "./Twofactor.svelte";

  const appname = "OpenAuth";

  const states = {
    credentials: 1,
    twofactor: 3,
    redirect: 4,
  };

  let username = Api.getUsername();
  let password = "";

  let loading = false;
  let state = states.credentials;

  function getButtonText(state) {
    switch (state) {
      case states.username:
        return "Next";
      case states.password:
        return "Login";
      default:
        return "";
    }
  }

  $: btnText = getButtonText(state);

  let error;

  // window.addEventListener("popstate", () => {
  //    state = history.state;
  // })

  function LoadRedirect() {
    state = states.redirect;
  }

  function Loading() {
    state = states.loading;
  }

  let salt;
  async function buttonClick() {
    if (state === states.username) {
      Loading();
      let res = await Api.setUsername(username);
      if (res.error) {
        error = res.error;
        LoadUsername();
      } else {
        LoadPassword();
      }
    } else if (state === states.password) {
      Loading();
      let res = await Api.setPassword(password);
      if (res.error) {
        error = res.error;
        LoadPassword();
      } else {
        if (res.tfa) {
          // TODO: Make TwoFactor UI/-s
        } else {
          LoadRedirect();
        }
      }
      btnText = "Error";
    }
  }

  function startRedirect() {
    state = states.redirect;
    // Show message to User and then redirect
    setTimeout(() => Api.finish(), 2000);
  }

  function afterCredentials() {
    Object.keys(Api); // Some weird bug needs this???

    if (Api.twofactor) {
      state = states.twofactor;
    } else {
      startRedirect();
    }
  }

  function afterTwoFactor() {
    startRedirect();
  }
</script>

<style>
  footer {
    text-align: center;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
  }
</style>

<Theme>
  <HoveringContentBox title="Login" {loading}>
    <form action="JavaScript:void(0)">
      {#if state === states.redirect}
        <Redirect />
      {:else if state === states.credentials}
        <Credentials next={afterCredentials} setLoading={(s) => (loading = s)} />
      {:else if state === states.twofactor}
        <Twofactor finish={afterTwoFactor} setLoading={(s) => (loading = s)} />
      {/if}
    </form>
  </HoveringContentBox>
  <footer>
    <p>Powered by {appname}</p>
  </footer>
</Theme>
