<template>
  <q-layout view="hHh lpr lFf">
    <q-header elevated class="bg-primary text-white">
      <q-toolbar>
        <q-btn
          v-if="!leftDrawerOpen"
          dense
          flat
          round
          icon="menu"
          @click="leftDrawerOpen = !leftDrawerOpen"
        />

        <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="leftDrawerOpen"
      show-if-above
      side="left"
      bordered
      :mini="leftDrawerMini"
      @click.capture="leftDrawerClicker"
    >
      <!-- 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>

      <div class="q-mini-drawer-hide absolute" style="top: 15px; right: -11px">
        <q-btn
          size="sm"
          dense
          round
          unelevated
          color="secondary"
          icon="mdi-menu-left"
          @click="leftDrawerMini = true"
        />
      </div>

      <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(false);
    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');

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

    const leftDrawerOpen = computed({
      get: () => (leftDrawer.value || Screen.gt.sm ? true : false),
      set: (val: boolean) => (leftDrawer.value = val),
    });

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

    function leftDrawerClicker() {
      if (leftDrawerMini.value) {
        leftDrawerMini.value = false;
      }
    }

    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,
      leftDrawerOpen,
      leftDrawerMini,
      leftDrawerClicker,
      logout,
      mainLinks,
      notifications,
      noPermission,
      remove,
      requestPermission,
      shortcuts,
      subLinks,
      useNative,
    };
  },
});
</script>
