<template>
  <q-layout view="hHh Lpr lff">
    <q-header elevated class="bg-primary text-white">
      <q-toolbar>
        <q-btn dense flat round icon="mdi-menu" @click="openMenu" />

        <q-toolbar-title>
          <router-link :to="{ name: 'dashboard' }" style="text-decoration: none; color: inherit">
            <q-avatar rounded>
              <img src="flaschengeist-logo-white.svg" />
            </q-avatar>
            <span class="gt-xs"> Flaschengeist </span>
          </router-link>
        </q-toolbar-title>

        <!-- Hier kommen die Shortlinks hin -->
        <q-btn icon="mdi-message-bulleted" flat dense
          ><q-badge color="negative" floating>{{ notifications.length }}</q-badge>
          <q-menu style="max-height: 400px; overflow: auto">
            <q-btn
              v-if="useNative && noPermission"
              label="Benachrichtigungen erlauben"
              @click="requestPermission"
            />
            <template v-if="notifications.length > 0">
              <Notification
                v-for="(notification, index) in notifications"
                :key="index"
                :model-value="notification"
                @remove="remove"
              />
            </template>
            <div v-else class="q-pa-sm">Keine neuen Benachrichtigungen</div>
          </q-menu>
        </q-btn>
        <shortcut-link
          v-for="(shortcut, index) in shortcuts"
          :key="'shortcut' + index"
          :shortcut="shortcut"
        />
        <q-btn flat round dense icon="mdi-exit-to-app" @click="logout()" />
      </q-toolbar>
    </q-header>

    <q-drawer
      v-model="leftDrawer"
      side="left"
      bordered
      :mini="leftDrawerMini"
      @click.capture="openMenu"
    >
      <!-- Plugins -->
      <q-list>
        <essential-link
          v-for="(entry, index) in mainLinks"
          :key="'plugin' + index"
          :entry="entry"
        />
        <q-separator />
        <!-- Plugin functions -->
        <essential-link
          v-for="(entry, index) in subLinks"
          :key="'childPlugin' + index"
          :entry="entry"
        />
      </q-list>
      <q-separator />
      <essential-link
        v-for="(entry, index) in essentials"
        :key="'essential' + index"
        :entry="entry"
      />
    </q-drawer>
    <q-page-container>
      <router-view />
    </q-page-container>
  </q-layout>
</template>

<script lang="ts">
import EssentialLink from 'src/components/navigation/EssentialLink.vue';
import ShortcutLink from 'src/components/navigation/ShortcutLink.vue';
import Notification from 'src/components/Notification.vue';
import { defineComponent, ref, inject, computed, onBeforeMount, onBeforeUnmount } from 'vue';
import { useMainStore } from 'src/stores';
import { FG_Plugin } from 'src/plugins';
import { useRouter } from 'vue-router';
import { Screen } from 'quasar';
import config from 'src/config';

const essentials: FG_Plugin.MenuLink[] = [
  {
    title: 'Über Flaschengeist',
    link: 'about',
    icon: 'mdi-information',
  },
];

export default defineComponent({
  name: 'MainLayout',
  components: { EssentialLink, ShortcutLink, Notification },
  setup() {
    const router = useRouter();
    const mainStore = useMainStore();
    const flaschengeist = inject<FG_Plugin.Flaschengeist>('flaschengeist');
    const leftDrawer = ref(true);
    const leftDrawerMini = ref(false);
    const shortcuts = flaschengeist?.shortcuts || [];
    const mainLinks = flaschengeist?.menuLinks || [];
    const notifications = computed(() => mainStore.notifications.slice().reverse());
    const polling = ref(NaN);
    const useNative = 'Notification' in window && window.Notification !== undefined;
    const noPermission = ref(!useNative || window.Notification.permission !== 'granted');

    const subLinks = computed(() => {
      const matched = router.currentRoute.value.matched[1];
      return flaschengeist?.menuLinks.find((link) => matched.name == link.link)?.children;
    });

    onBeforeMount(() => {
      polling.value = window.setInterval(() => pollNotification(), config.pollingInterval);
      pollNotification();
    });
    onBeforeUnmount(() => window.clearInterval(polling.value));

    function openMenu(event: { target: HTMLInputElement }) {
      if (event.target.nodeName === 'DIV') leftDrawerMini.value = false;
      else {
        if (!leftDrawer.value || leftDrawerMini.value) {
          leftDrawer.value = true;
          leftDrawerMini.value = false;
        } else {
          leftDrawerMini.value = Screen.gt.sm && !leftDrawerMini.value;
          leftDrawer.value = leftDrawerMini.value;
        }
      }
    }

    function logout() {
      void router.push({ name: 'login', params: { logout: 'logout' } });
      void mainStore.logout();
    }

    async function remove(id: number) {
      await mainStore.removeNotification(id);
    }

    function requestPermission() {
      void window.Notification.requestPermission().then(
        (p) => (noPermission.value = p !== 'granted')
      );
    }

    function pollNotification() {
      void mainStore
        .loadNotifications(<FG_Plugin.Flaschengeist>flaschengeist)
        .then((notifications) => {
          if (useNative && !noPermission.value)
            notifications.forEach(
              (notif) =>
                new window.Notification(notif.text, {
                  timestamp: notif.time.getTime(),
                })
            );
        });
    }

    return {
      essentials,
      leftDrawer,
      leftDrawerMini,
      logout,
      mainLinks,
      notifications,
      noPermission,
      openMenu,
      remove,
      requestPermission,
      shortcuts,
      subLinks,
      useNative,
    };
  },
});
</script>