<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 ref="LoginForm" class="q-gutter-md" @submit="doLogin">
          <q-input
            v-model="userid"
            filled
            label="Benutzername oder E-Mail"
            :rules="rules"
            tabindex="1"
          />
          <q-input
            v-model="password"
            filled
            type="password"
            label="Password"
            :rules="rules"
            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 { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { Loading, Notify } from 'quasar';
import { defineComponent, ref } from 'vue';
import { setBaseUrl, api } from 'boot/axios';
import { UserSessionState } from 'src/plugins/user/store';

export default defineComponent({
  // name: 'PageName'
  setup() {
    const store = useStore<UserSessionState>();
    const router = useRouter();
    const mainRoute = { name: 'dashboard' };

    /* Stuff for the real login page */
    const userid = ref('');
    const password = ref('');
    const rules = [(val: string) => (val && val.length > 0) || 'Feld darf nicht leer sein!'];
    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);
      }
    }

    function doLogin() {
      Loading.show({
        message: 'Du wirst angemeldet',
      });
      store
        .dispatch('sessions/login', {
          userid: userid.value,
          password: password.value,
        })
        .then(() => {
          const x = router.currentRoute.value.query['redirect'];
          void router.push(typeof x === 'string' ? { path: x } : mainRoute);
        })
        .catch((error: { status: number } | undefined) => {
          if (error && error.status === 401) {
            password.value = '';
            Notify.create({
              group: false,
              type: 'negative',
              message: 'Benutzername oder Passwort sind falsch.',
              timeout: 10000,
              progress: true,
              actions: [{ icon: 'mdi-close', color: 'white' }],
            });
          }
        })
        .finally(() => {
          Loading.hide();
        });
    }

    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;
      }
      void store
        .dispatch('sessions/requestPasswordReset', {
          userid: userid.value,
        })
        .then(() => {
          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 {
      userid,
      password,
      doLogin,
      doReset,
      rules,
      server,
      changeUrl,
      visible,
      openServerSettings,
    };
  },
});
</script>
