<script setup>
import { useRoute, useRouter } from "vue-router";
import { useLight, q, m } from "#imports";
import { useQuasar, setCssVar, getCssVar } from "quasar";
import { useI18n } from "vue-i18n";
import { ref, computed, reactive, provide, watch, toRaw, onMounted } from "vue";
import { useRuntimeConfig } from "nuxt/app";
import { logout } from "@hostlink/light";
const emits = defineEmits(["logout"]);
defineProps({
  userMenuItems: { type: Array, required: false },
  headerButtons: { type: Array, required: false }
});
const $q = useQuasar();
$q.loading.show();
const config = useRuntimeConfig();
const appVersion = config.public.appVersion ?? "0.0.1";
const tt = await q({
  system: {
    devMode: true,
    time: true,
    storage: {
      freeSpace: true,
      usageSpace: true,
      totalSpace: true
    }
  },
  app: {
    menus: true,
    viewAsMode: true,
    languages: true,
    copyrightName: true,
    copyrightYear: true,
    hasFavorite: true,
    notificationBellEnabled: true,
    i18nMessages: {
      name: true,
      value: true
    }
  },
  my: {
    username: true,
    first_name: true,
    last_name: true,
    roles: true,
    styles: true,
    language: true,
    permissions: true,
    default_page: true,
    myFavorites: {
      my_favorite_id: true,
      label: true,
      path: true,
      icon: true
    },
    menu: true
  }
});
let app = tt.app;
let my = reactive(tt.my);
const light = useLight();
light.devMode = tt.system.devMode;
light.init(my.styles);
const color = light.getColorValue();
setCssVar("primary", color);
light.setMyRoles(my.roles);
light.setPermissions(my.permissions);
light.setMyFavorites(toRaw(my.myFavorites));
const myFavorites = computed(() => {
  return light.getMyFavorites();
});
const myFavoritesCount = computed(() => {
  return light.getMyFavorites().length;
});
$q.dark.set(light.isDarkMode());
const i18n = useI18n();
i18n.locale.value = my.language || "en";
let system = tt.system;
let messages = i18n.messages.value[i18n.locale.value] || {};
for (let t of app.i18nMessages) {
  messages[t.name] = t.value;
}
i18n.setLocaleMessage(i18n.locale.value, messages);
const menus = ref(app.menus);
const my_menus = ref(my.menu);
const leftDrawerOpen = ref(false);
const rightDrawerOpen = ref(false);
const toggleLeftDrawer = () => {
  leftDrawerOpen.value = !leftDrawerOpen.value;
};
const toggleRightDrawer = () => {
  rightDrawerOpen.value = !rightDrawerOpen.value;
};
let showViewAs = false;
if (my && my.roles.indexOf("Administrators") != -1) {
  showViewAs = true;
  light.isAdmin = true;
}
const layoutView = computed(() => {
  let s = "";
  s += style.menuOverlayHeader ? "l" : "h";
  s += "Hh LpR lFr";
  return s;
});
const style = reactive({
  miniState: my.styles?.miniState || false,
  dense: my.styles?.dense || false,
  footer: my.styles?.footer || false,
  menuOverlayHeader: my.styles?.menuOverlayHeader || false
});
const isMouseOnDrawer = ref(false);
const isMini = computed(() => {
  if (isMouseOnDrawer.value) {
    return false;
  }
  if (style.miniState) {
    return true;
  }
  return false;
});
const menuDark = computed(() => {
  if (light.theme == "dark") {
    return true;
  }
  if (light.theme == "semi-dark") {
    return true;
  }
  return false;
});
const languages = app.languages;
const onChangeLocale = async (locale) => {
  localStorage.setItem("locale", locale);
  await m("updateMyLanguage", { name: locale });
  window.location.reload();
};
const reloadMenu = async () => {
  let { app: app2, my: my2 } = await q({
    app: {
      menus: true
    },
    my: {
      menu: true
    }
  });
  menus.value = app2.menus;
  my_menus.value.menu = my2.menu;
};
provide("reloadMenu", reloadMenu);
watch(() => style.footer, async (value) => await light.setStyle("footer", value));
watch(() => style.dense, async (value) => await light.setStyle("dense", value));
watch(() => light.theme, async () => {
  $q.dark.set(light.isDarkMode());
});
watch(() => style.menuOverlayHeader, async (value) => {
  await light.setStyle("menuOverlayHeader", value);
});
watch(() => style.miniState, async (value) => {
  await m("updateMyStyle", {
    name: "miniState",
    value
  });
});
const exitViewAs = async () => {
  await m("cancelViewAs");
  window.location.reload();
};
const storageColor = computed(() => {
  if (system.storage) {
    const percent = system.storage.freeSpace / system.storage.totalSpace;
    if (percent < 0.05) {
      return "negative";
    }
    if (percent < 0.1) {
      return "warning";
    }
  }
});
const containerClass = computed(() => {
  return light.theme == "dark" ? {} : { "bg-grey-2": true };
});
const containerStyle = computed(() => {
  if (light.theme == "dark") {
    return {};
  }
  return {
    color: "#1f1f1f"
  };
});
const route = useRoute();
const router = useRouter();
const onToggleFav = async () => {
  if (isFav.value) {
    await m("removeMyFavorite", {
      path: route.fullPath
    });
    light.reloadMyFavorites();
    return;
  }
  light.dialog({
    title: "Add to favorite",
    message: "Enter favorite label",
    prompt: {
      //get window title, remove - and replace with space
      model: String(route.name || "Untitled").replace(/-/g, " "),
      isValid: (val) => val !== ""
    },
    cancel: true,
    persistent: true
  }).onOk(async (data) => {
    if (await m("addMyFavorite", {
      path: route.fullPath,
      label: data
    })) {
      light.reloadMyFavorites();
    }
  });
};
const isFav = computed(() => {
  let fav = my.myFavorites.find((item) => {
    return item.path == route.fullPath;
  });
  return fav;
});
$q.loading.hide();
const menuWidth = ref(my.styles.menuWidth || 280);
watch(menuWidth, () => {
  light.setStyle("menuWidth", menuWidth.value);
});
const c1 = computed(() => {
  return light.getColorValue();
});
if (route.fullPath == "/" && my.default_page) {
  router.push(my.default_page);
}
const onLogout = async () => {
  await logout();
  emits("logout");
};
</script>

<style scoped>
.q-layout__section--marginal{background-color:v-bind(c1)}
</style>

<template>
    <q-layout :view="layoutView">
        <q-header bordered class="text-white" :class="`bg-${light.color}`">
            <q-toolbar>
                <q-btn dense flat round icon="sym_o_menu" class="q-mr-sm" @click="toggleLeftDrawer" />

                <q-toolbar-title>
                    {{ light.company }}
                    <template v-if="tt.system.devMode">
                        <span style="font-size: 0.8em;">[Dev mode]</span>
                    </template>
                </q-toolbar-title>

                <q-space />

                <slot name="header"></slot>

                <!-- Header buttons (desktop) -->
                <template v-for="button in headerButtons || []" :key="button.name">
                    <q-btn v-if="button.visible !== false && button.desktop !== false" round flat dense
                        :icon="button.icon" class="q-mr-sm gt-xs" @click="button.click"
                        :to="button.to ? button.to : void 0">
                        <q-tooltip v-if="button.tooltip">{{ $t(button.tooltip) }}</q-tooltip>
                        <q-menu v-if="button.menu">
                            <slot :name="`header-button-menu-${button.name}`"></slot>
                        </q-menu>
                    </q-btn>
                </template>

                <!-- Header buttons (mobile hamburger) -->
                <q-btn round flat dense icon="menu" class="q-mr-sm lt-sm" v-if="headerButtons?.length">
                    <q-tooltip>More</q-tooltip>
                    <q-menu>
                        <q-list>
                            <template v-for="button in headerButtons || []" :key="button.name">
                                <q-item v-if="button.visible !== false && button.mobile !== false"
                                    :clickable="!button.menu && (!!button.to || !!button.click)" @click="button.click"
                                    :to="button.to ? button.to : void 0">
                                    <q-item-section avatar>
                                        <q-icon :name="button.icon" />
                                    </q-item-section>
                                    <q-item-section>{{ button.tooltip ? $t(button.tooltip) : button.name
                                        }}</q-item-section>
                                    <q-item-section side v-if="button.menu">
                                        <q-btn flat dense icon="arrow_right">
                                            <q-menu anchor="top end" self="top start">
                                                <slot :name="`header-button-menu-${button.name}`"></slot>
                                            </q-menu>
                                        </q-btn>
                                    </q-item-section>
                                </q-item>
                            </template>
                        </q-list>
                    </q-menu>
                </q-btn>

                <q-btn :icon="isFav ? 'favorite' : 'sym_o_favorite'" round flat dense class="q-mr-xs"
                    @click="onToggleFav" v-if="app.hasFavorite">
                </q-btn>

                <q-btn :icon="$q.fullscreen.isActive ? 'fullscreen_exit' : 'fullscreen'" round flat dense
                    class="q-mr-xs" @click="$q.fullscreen.toggle()">
                    <q-tooltip>
                        {{ $q.fullscreen.isActive ? $t("Exit Fullscreen") : $t("Fullscreen") }}
                    </q-tooltip>
                </q-btn>

                <q-btn v-if="languages.length > 1" round flat dense icon="language" class="q-mr-xs">
                    <q-tooltip>
                        {{ my.language }}
                    </q-tooltip>
                    <q-menu>
                        <q-list>
                            <q-item v-for="language in languages" :key="language.value" v-close-popup clickable
                                @click="onChangeLocale(language.value)" :active="language.value == my.language">
                                <q-item-section>
                                    <q-item-label>{{ language.name }}</q-item-label>
                                </q-item-section>
                            </q-item>
                        </q-list>
                    </q-menu>
                </q-btn>

                <q-btn icon="sym_o_storage" flat round dense class="q-mr-sm" v-if="system.storage"
                    :color="storageColor">
                    <q-menu>
                        <l-storage :storage="system.storage" style="width:250px" />
                    </q-menu>
                </q-btn>

                <l-notification-bell class="q-mr-xs" v-if="app.notificationBellEnabled !== false" />

                <div class="q-mx-sm" v-if="$q.screen.gt.xs">
                    <div class="text-bold text-right">
                        {{ my.first_name }} {{ my.last_name }}
                    </div>

                    <div class="text-right ellipsis" style="max-width: 120px;">
                        {{ my.roles.join(", ") }}
                        <q-tooltip>
                            {{ my.roles.join(", ") }}
                        </q-tooltip>
                    </div>
                </div>

                <q-btn flat round dense icon="sym_o_person" class="q-mr-sm">
                    <q-menu max-width="250px">
                        <q-list :dense="style.dense">
                            <q-item v-close-popup to="/User/profile">
                                <q-item-section avatar>
                                    <q-icon name="sym_o_person" />
                                </q-item-section>
                                <q-item-section>{{ $t("Profile") }}</q-item-section>
                            </q-item>

                            <q-item v-close-popup to="/User/setting">
                                <q-item-section avatar>
                                    <q-icon name="sym_o_settings_account_box" />
                                </q-item-section>
                                <q-item-section>{{ $t("Settings") }}</q-item-section>
                            </q-item>

                            <q-item v-close-popup v-if="showViewAs" to="/System/view_as">
                                <q-item-section avatar>
                                    <q-icon name="sym_o_visibility" />
                                </q-item-section>
                                <q-item-section>{{ $t("View as") }}</q-item-section>
                            </q-item>

                            <q-item v-close-popup v-if="app.viewAsMode" @click="exitViewAs" clickable>
                                <q-item-section avatar>
                                    <q-icon name="sym_o_visibility_off" />
                                </q-item-section>
                                <q-item-section>{{ $t("Exit view as") }}</q-item-section>
                            </q-item>

                            <slot name="user-menu"></slot>

                            <q-item v-for="item in userMenuItems || []" :key="item.label" v-close-popup :to="item.to"
                                clickable @click="item.click" v-show="item.visible !== false">
                                <q-item-section avatar v-if="item.icon">
                                    <q-icon :name="item.icon" />
                                </q-item-section>
                                <q-item-section>
                                    <q-item-label>{{ $t(item.label) }}</q-item-label>
                                </q-item-section>
                            </q-item>

                            <q-separator />

                            <q-item @click="onLogout" clickable>
                                <q-item-section avatar>
                                    <q-icon name="logout" />
                                </q-item-section>
                                <q-item-section>{{ $t("Logout") }}</q-item-section>
                            </q-item>

                        </q-list>
                    </q-menu>
                </q-btn>

                <q-btn dense flat round icon="sym_o_menu" @click="toggleRightDrawer" />
            </q-toolbar>
        </q-header>

        <q-drawer v-model="leftDrawerOpen" bordered show-if-above side="left" :dark="menuDark" :width="menuWidth"
            :mini-to-overlay="style.miniState" :mini="isMini" @mouseout="isMouseOnDrawer = false"
            @mouseover="isMouseOnDrawer = true">
            <!-- drawer content -->
            <q-scroll-area class="fit">
                <div class="q-mx-xs q-mt-xs">
                    <l-menu :value="my_menus" :dense="style.dense" />
                    <l-fav-menu :value="myFavorites" :dense="style.dense" v-if="myFavoritesCount > 0" />
                    <l-menu :value="menus" :dense="style.dense" />
                </div>
            </q-scroll-area>
        </q-drawer>

        <q-drawer overlay v-model="rightDrawerOpen" side="right" bordered>
            <!-- drawer content -->
            <q-scroll-area class="fit">
                <l-customizer v-model:color="light.color" v-model:theme="light.theme"
                    v-model:miniState="style.miniState" v-model:dense="style.dense"
                    v-model:menuOverlayHeader="style.menuOverlayHeader" v-model:footer="style.footer"
                    v-model:menuWidth="menuWidth" :time="system.time" />
            </q-scroll-area>
        </q-drawer>

        <q-page-container :class="containerClass" :style="containerStyle"> <!-- Error message -->
            <div class="q-gutter-sm q-pa-sm" v-if="system.devMode && $light.errors.length > 0">
                <q-banner dense inline-actions class="bg-grey-4" v-for="error in $light.errors" rounded>
                    {{ error }}
                    <template v-slot:action>
                        <q-btn flat icon="sym_o_close" round dense @click="$light.removeError(error)" />
                    </template>
                </q-banner>

            </div>

            <!-- router-view v-slot="{ Component }">

                <template v-if="Component">
                    <suspense>
                        <component :is="Component" :reloadMenu="reloadMenu"></component>
                    </suspense>
                </template>
            </router-view -->
            <NuxtLoadingIndicator />
            <slot name="page-top"></slot>
            <NuxtPage />
            <slot name="page-bottom"></slot>
        </q-page-container>
        <q-footer bordered v-if="style.footer">
            <q-item>
                <q-item-section>
                    {{ light.company }} {{ appVersion }} - Copyright {{ app.copyrightYear }} {{ app.copyrightName
                    }}. Build
                    {{ light.version }}
                </q-item-section>
            </q-item>
        </q-footer>
    </q-layout>
</template>
