<template>
  <div class="column is-3-widescreen is-4-desktop is-5-tablet">
    <form class="box" @submit.prevent="doAction">
      <div v-if="errorMessage" class="notification is-danger">
        {{ errorMessage }}
      </div>

      <b-field label="Benutzername">
        <b-input type="text" v-model="user.username" />
      </b-field>
      <b-field label="Kennwort">
        <b-input type="password" v-model="user.password" />
      </b-field>
      <b-field v-if="mode === 'signup'" label="Kennwort wiederholen">
        <b-input type="password" v-model="password2" />
      </b-field>

      <div class="buttons">
        <b-button native-type="submit" type="is-primary">
          {{ mode === "login" ? "Anmelden" : "Konto anlegen" }}
        </b-button>
        <router-link v-if="mode === 'login'" to="/signup"
          >Konto anlegen</router-link
        >
        <router-link v-else to="/login">Anmelden</router-link>
      </div>
    </form>
  </div>
</template>

<script lang="ts">
import { Component, Watch } from "vue-property-decorator";
import { user } from "@/api";
import { NotifyMixin } from "@/mixins";
import { mixins } from "vue-class-component";
import { Route } from "vue-router";

@Component
export default class Login extends mixins(NotifyMixin) {
  user = user;
  private mode: "login" | "signup" = "login";
  private password2 = "";
  private errorMessage = "";

  public created(): void {
    if (this.$route.name === "signup") this.mode = "signup";
  }

  @Watch("$route")
  public routeChanged(to: Route): void {
    if (to.name === "signup") {
      this.mode = "signup";
    } else {
      this.mode = "login";
    }
  }

  private async doAction() {
    try {
      if (this.mode === "login") {
        await this.user.login();
        if (this.$route.name !== "home") this.$router.push({ name: "home" });
      } else {
        await this.user.signup();
        this.$router.push({ name: "login" });
        this.showSuccess("Du kannst dich nun anmelden.");
      }
    } catch {
      this.errorMessage = "Fehler";
    }
  }
}
</script>
