<template>
  <ion-page>
    <m6-header />
    <ion-content :fullscreen="true">
      <form id="login">
        <h2>Sign in</h2>
        <div class="item">
          <input placeholder="username" type="text" v-model="form.username" />
        </div>
        <div class="item">
          <input
            placeholder="password"
            type="password"
            v-model="form.password"
          />
        </div>
        <ion-button color="primary" id="log" @click="handleLogin()">
          Submit
        </ion-button>
      </form>
    </ion-content>
    <m6-footer />
  </ion-page>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { IonPage, IonContent } from "@ionic/vue";
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";

import { mapGetters, mapActions } from "vuex";

export default defineComponent({
  name: "Sign",
  components: {
    IonContent,
    IonPage,
    "m6-header": Header,
    "m6-footer": Footer,
  },
  data() {
    return {
      form: { username: "", password: "" },
    };
  },
  computed: {
    ...mapGetters("auth", ["isLogged"]),
  },
  created() {
    if (this.isLogged) window.location.href = "/me";
  },
  methods: {
    handleLogin() {
      if (this.form.username == "" || this.form.password == "") {
        this.toast({
          header: "All fields are required",
          text: "",
          color: "danger",
        });
        return;
      }
      this.login(this.form).then((response) => {
        if (response.status != 200) {
          this.toast({
            header: response.data.error,
            text: "",
            color: "danger",
          });
        } else {
          this.toast({
            header: "Logged successfully",
            text: "",
            color: "success",
          });
          setTimeout(() => {
            window.location.href = "/me";
          }, 2000);
        }
      });
    },
    ...mapActions(["toast"]),
    ...mapActions("auth", ["login"]),
  },
});
</script>
