<template>
  <q-page padding class="fit row justify-center items-center content-center">
    <q-card class="col-xs-11 col-sm-8 col-md-6 col-lg-4 justify-center items-center content-center">
      <q-toolbar class="bg-primary text-white">
        <q-toolbar-title> Login </q-toolbar-title>
      </q-toolbar>

      <q-card-section>
        <q-form class="q-gutter-md" @submit="doLogin">
          <q-input
            v-model="userid"
            filled
            label="Benutzername oder E-Mail"
            autocomplete="username"
            :rules="[notEmpty]"
            tabindex="1"
          />
          <password-input
            v-model="password"
            filled
            label="Passwort"
            autocomplete="cureent-password"
            :rules="[notEmpty]"
            tabindex="2"
          />
          <div class="row justify-between">
            <q-btn
              label="Passwort vergessen"
              type="a"
              color="secondary"
              tabindex="4"
              @click="doReset"
            />
            <q-btn label="Login" type="submit" color="primary" tabindex="3" />
          </div>
        </q-form>
      </q-card-section>
      <div class="row justify-end">
        <q-btn flat round icon="mdi-menu-down" class="cordova-only" @click="openServerSettings" />
      </div>
      <q-slide-transition class="cordova-only">
        <div v-show="visible">
          <q-separator />
          <q-card-section>
            <q-form ref="ServerSettingsForm" class="q-gutter-md" @submit="changeUrl">
              <div class="text-h6">Servereinstellung</div>
              <q-input v-model="server" filled label="Server" dense />
              <q-btn size="xs" dense color="primary" label="Speichern" type="submit" />
            </q-form>
          </q-card-section>
        </div>
      </q-slide-transition>
    </q-card>
  </q-page>
</template>

<script lang="ts">
import { useRouter } from 'vue-router';
import { Loading, Notify } from 'quasar';
import { useMainStore } from 'src/stores';
import { defineComponent, ref } from 'vue';
import { setBaseURL, api } from 'boot/axios';
import { notEmpty } from 'src/utils/validators';
import { useUserStore } from 'src/plugins/user/store';
import PasswordInput from 'src/components/utils/PasswordInput.vue';

export default defineComponent({
  name: 'Login',
  components: { PasswordInput },
  setup() {
    const mainStore = useMainStore();
    const mainRoute = { name: 'dashboard' };
    const router = useRouter();

    /* Stuff for the real login page */
    const userid = ref('');
    const password = ref('');
    const server = ref<string | undefined>(api.defaults.baseURL);
    const visible = ref(false);

    function openServerSettings() {
      visible.value = !visible.value;
    }

    function changeUrl() {
      if (server.value) {
        setBaseURL(server.value);
      }
    }

    async function doLogin() {
      Loading.show({ message: 'Du wirst angemeldet' });
      const status = await mainStore.login(userid.value, password.value);

      if (status === true) {
        mainStore.user = (await useUserStore().getUser(userid.value)) || undefined;
        const x = router.currentRoute.value.query['redirect'];
        void router.push(typeof x === 'string' ? { path: x } : mainRoute);
      } else {
        password.value = '';
        if (status === 401) {
          Notify.create({
            group: false,
            type: 'negative',
            message: 'Benutzername oder Passwort sind falsch.',
            timeout: 10000,
            progress: true,
            actions: [{ icon: 'mdi-close', color: 'white' }],
          });
        }
      }
      Loading.hide();
    }

    async function doReset() {
      if (userid.value == '') {
        Notify.create({
          group: false,
          type: 'negative',
          message: 'Der Benutzername darf nicht leer sein.',
          timeout: 10000,
          progress: true,
          actions: [{ icon: 'mdi-close', color: 'white' }],
        });
        return;
      }

      if (await mainStore.requestReset(userid.value)) {
        userid.value = '';
        password.value = '';
        Notify.create({
          group: false,
          type: 'ongoing',
          message:
            'Sollte der Benutzername korrekt und vorhanden sein, erhälst du jetzt eine E-Mail.',
          timeout: 10000,
          progress: true,
          actions: [{ icon: 'mdi-close', color: 'white' }],
        });
      }
    }

    return {
      changeUrl,
      doLogin,
      doReset,
      notEmpty,
      openServerSettings,
      password,
      server,
      userid,
      visible,
    };
  },
});
</script>
