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

    <div class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">Login</p>
        <button
          class="delete"
          aria-label="close"
          @click.left="$emit('cancel')"
        />
      </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">Passwort</label>
          <div class="control">
            <input class="input" type="password" v-model="password" />
          </div>
        </div>
      </section>

      <footer class="modal-card-foot is-flex is-justify-content-space-around">
        <BulmaButton
          class="button is-success"
          @click.left="$emit('submit', username, password)"
          icon="fa-solid fa-unlock"
          text="Login"
        />
        <BulmaButton
          class="button is-danger"
          @click.left="$emit('cancel')"
          icon="fa-solid fa-circle-xmark"
          text="Abbrechen"
        />
      </footer>
    </div>
  </div>
</template>

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

import BulmaButton from "./bulma/Button.vue";

@Options({
  components: {
    BulmaButton,
  },
  props: {
    visible: Boolean,
  },
  emits: ["cancel", "submit"],
})
export default class extends Vue {
  public username = "";
  public password = "";

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

  private on_keydown(e: KeyboardEvent) {
    if (e.key == "Escape") this.$emit("cancel");
    else if (e.key == "Enter")
      this.$emit("submit", this.username, this.password);
  }

  public mounted(): void {
    window.addEventListener("keydown", this.on_keydown);

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

  public beforeUnmount(): void {
    window.removeEventListener("keydown", this.on_keydown);
  }
}
</script>
