<template>
  <div v-show="active" class="modal is-active">
    <div class="modal-background" />

    <div class="modal-card">
      <form @submit.prevent="submit">
        <header class="modal-card-head">
          <p class="modal-card-title">Login</p>
          <button
            class="delete"
            aria-label="close"
            @click.left="set_active(false)"
          />
        </header>

        <section class="modal-card-body">
          <div class="field">
            <label class="label">Username</label>
            <div class="control">
              <input
                ref="username_input"
                class="input"
                type="text"
                v-model="username"
              />
            </div>
          </div>

          <div class="field">
            <label class="label">Password</label>
            <div class="control">
              <input class="input" type="password" v-model="password" />
            </div>
          </div>
        </section>

        <footer class="modal-card-foot">
          <button class="button is-success" @click.left="submit">Login</button>
          <button class="button is-danger" @click.left="set_active(false)">
            Cancel
          </button>
        </footer>
      </form>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue } from "vue-class-component";

export default class extends Vue {
  public active = false;
  public username = "";
  public password = "";

  declare $refs: {
    username_input: HTMLInputElement | null | undefined;
  };

  public created() {
    window.addEventListener("keydown", (e) => {
      if (e.key == "Escape") this.set_active(false);
    });
  }

  public set_active(state: boolean) {
    this.active = state;

    this.username = "";
    this.password = "";

    if (this.active) {
      this.$nextTick(() => {
        if (this.$refs.username_input instanceof HTMLInputElement) {
          this.$refs.username_input?.focus();
        }
      });
    }
  }

  public submit() {
    this.$advent22.set_api_auth(this.username, this.password);
    this.set_active(false);
  }
}
</script>
