<script setup>

import { useI18n } from 'vue-i18n';
const i18n = useI18n();
const t = i18n.t;

import { onMounted, onUnmounted, ref, useTemplateRef, provide } from 'vue';
import { Notification, InputDialog, fetcher } from '@cloudron/pankow';
import { setLanguage } from './i18n.js';
import { API_ORIGIN, TOKEN_TYPES } from './constants.js';
import { redirectIfNeeded, startAuthFlow } from './utils.js';
import ProfileModel from './models/ProfileModel.js';
import ProvisionModel from './models/ProvisionModel.js';
import NotificationsModel from './models/NotificationsModel.js';
import DashboardModel from './models/DashboardModel.js';
import BrandingModel from './models/BrandingModel.js';
import Headerbar from './components/Headerbar.vue';
import SubscriptionRequiredDialog from './components/SubscriptionRequiredDialog.vue';
import RequestErrorDialog from './components/RequestErrorDialog.vue';
import OfflineOverlay from './components/OfflineOverlay.vue';
import SideBar from './components/SideBar.vue';
import AppsView from './views/AppsView.vue';
import AppConfigureView from './views/AppConfigureView.vue';
import AppearanceView from './views/AppearanceView.vue';
import AppstoreView from './views/AppstoreView.vue';
import BackupSitesView from './views/BackupSitesView.vue';
import AppArchiveView from './views/AppArchiveView.vue';
import CloudronAccountView from './views/CloudronAccountView.vue';
import DomainsView from './views/DomainsView.vue';
import EmailDomainView from './views/EmailDomainView.vue';
import EmailDomainsView from './views/EmailDomainsView.vue';
import EmailMailboxesView from './views/EmailMailboxesView.vue';
import EmailMailinglistsView from './views/EmailMailinglistsView.vue';
import EmailSettingsView from './views/EmailSettingsView.vue';
import EmailEventlogView from './views/EmailEventlogView.vue';
import EventlogView from './views/EventlogView.vue';
import NetworkView from './views/NetworkView.vue';
import NotificationsView from './views/NotificationsView.vue';
import ProfileView from './views/ProfileView.vue';
import ServicesView from './views/ServicesView.vue';
import SystemSettingsView from './views/SystemSettingsView.vue';
import SystemUpdateView from './views/SystemUpdateView.vue';
import DockerView from './views/DockerView.vue';
import ServerView from './views/ServerView.vue';
import UserDirectorySettingsView from './views/UserDirectorySettingsView.vue';
import LdapView from './views/LdapView.vue';
import OpenIdView from './views/OpenIdView.vue';
import UsersView from './views/UsersView.vue';
import GroupsView from './views/GroupsView.vue';
import VolumesView from './views/VolumesView.vue';

const VIEWS = Object.freeze({
  APP: '#/app', // this is a prefix
  APPEARANCE: '#/appearance',
  APPS: '#/apps',
  APPSTORE: '#/appstore', // this is a prefix
  BACKUP_SITES: '#/backup-sites',
  APP_ARCHIVE: '#/app-archive',
  CLOUDRON_ACCOUNT: '#/cloudron-account',
  DOMAINS: '#/domains',
  EMAIL_DOMAIN: '#/email-domain',
  EMAIL_DOMAINS: '#/email-domains',
  MAILBOXES: '#/mailboxes',
  MAILINGLISTS: '#/mailinglists',
  EMAIL_SETTINGS: '#/email-settings',
  EMAIL_EVENTLOG: '#/email-eventlog',
  SERVER: '#/server',
  NETWORK: '#/network',
  NOTIFICATIONS: '#/notifications',
  PROFILE: '#/profile',
  SERVICES: '#/services',
  SYSTEM_SETTINGS: '#/system-settings',
  DOCKER: '#/docker',
  SYSTEM_EVENTLOG: '#/system-eventlog',
  SYSTEM_UPDATE: '#/system-update',
  USER_DIRECTORY_SETTINGS: '#/user-directory-settings',
  LDAP: '#/ldap',
  OPENID: '#/openid',
  USERS: '#/users',
  GROUPS: '#/groups',
  VOLUMES: '#/volumes',
});

const menuItems = ref([{
  label: t('apps.title'),
  icon: 'fa fa-grip fa-fw',
  route: VIEWS.APPS,
  active: () => view.value === VIEWS.APPS || view.value === VIEWS.APP,
}, {
  label: t('appstore.title'),
  icon: 'fa fa-cloud-download-alt fa-fw',
  route: VIEWS.APPSTORE,
  active: () => view.value === VIEWS.APPSTORE,
  visible: () => profile.value.isAtLeastAdmin,
}, {
  separator: true,
}, {
  label: t('domains.title'),
  icon: 'fa fa-globe fa-fw',
  route: VIEWS.DOMAINS,
  active: () => view.value === VIEWS.DOMAINS,
  visible: () => profile.value.isAtLeastAdmin,
}, {
  label: t('users.title'),
  icon: 'fa fa-users-gear fa-fw',
  visible: () => profile.value.isAtLeastUserManager,
  active: () => view.value === VIEWS.APPS || view.value === VIEWS.APP,
  childItems: [{
    label: t('main.navbar.users'),
    icon: 'fa fa-user fa-fw',
    route: VIEWS.USERS,
    active: () => view.value === VIEWS.USERS,
    visible: () => profile.value.isAtLeastUserManager,
  }, {
    label: t('main.navbar.groups'),
    icon: 'fa fa-users fa-fw',
    route: VIEWS.GROUPS,
    active: () => view.value === VIEWS.GROUPS,
    visible: () => profile.value.isAtLeastUserManager,
  }, {
    label: 'LDAP',
    icon: 'fa fa-fw fa-users-rays',
    route: VIEWS.LDAP,
    active: () => view.value === VIEWS.LDAP,
    visible: () => profile.value.isAtLeastAdmin,
  }, {
    label: 'OpenID',
    icon: 'fa fa-fw fa-brands fa-openid',
    route: VIEWS.OPENID,
    active: () => view.value === VIEWS.OPENID,
    visible: () => profile.value.isAtLeastAdmin,
  }, {
    label: t('userdirectory.settings.title'),
    icon: 'fa fa-fw fa-screwdriver-wrench',
    route: VIEWS.USER_DIRECTORY_SETTINGS,
    active: () => view.value === VIEWS.USER_DIRECTORY_SETTINGS,
    visible: () => profile.value.isAtLeastAdmin,
  }],
}, {
  label: t('emails.title'),
  icon: 'fa fa-envelope fa-fw',
  visible: () => profile.value.isAtLeastMailManager,
  childItems: [{
    label: 'Domains',
    icon: 'fa fa-fw fa-globe',
    route: VIEWS.EMAIL_DOMAINS,
    active: () => view.value === VIEWS.EMAIL_DOMAINS || view.value === VIEWS.EMAIL_DOMAIN,
    visible: () => profile.value.isAtLeastAdmin,
  }, {
    label: t('email.incoming.mailboxes.title'),
    icon: 'fa fa-fw fa-inbox',
    route: VIEWS.MAILBOXES,
    active: () => view.value === VIEWS.MAILBOXES,
  }, {
    label: t('email.incoming.mailinglists.title'),
    icon: 'fa fa-fw-solid fa-envelopes-bulk',
    route: VIEWS.MAILINGLISTS,
    active: () => view.value === VIEWS.MAILINGLISTS,
  }, {
    label: t('emails.eventlog.title'),
    icon: 'fa fa-fw fa-list-alt',
    route: VIEWS.EMAIL_EVENTLOG,
    active: () => view.value === VIEWS.EMAIL_EVENTLOG,
    visible: () => profile.value.isAtLeastAdmin,
  }, {
    label: t('emails.settings.title'),
    icon: 'fa fa-fw fa-screwdriver-wrench',
    route: VIEWS.EMAIL_SETTINGS,
    active: () => view.value === VIEWS.EMAIL_SETTINGS,
    visible: () => profile.value.isAtLeastAdmin,
  }]
}, {
  label: t('network.title'),
  icon: 'fas fa-network-wired fa-fw',
  route: VIEWS.NETWORK,
  active: () => view.value === VIEWS.NETWORK,
  visible: () => profile.value.isAtLeastAdmin,
}, {
  label: t('volumes.title'),
  icon: 'fa fa-hdd fa-fw',
  route: VIEWS.VOLUMES,
  active: () => view.value === VIEWS.VOLUMES,
  visible: () => profile.value.isAtLeastAdmin,
}, {
  label: t('backups.title'),
  icon: 'fa fa-archive fa-fw',
  visible: () => profile.value.isAtLeastAdmin,
  childItems: [{
    label: t('backups.sites.title'),
    icon: 'fa fa-fw fa-hard-drive',
    route: VIEWS.BACKUP_SITES,
    active: () => view.value === VIEWS.BACKUP_SITES,
  }, {
    label: t('backups.archives.title'),
    icon: 'fa fa-fw fa-grip',
    route: VIEWS.APP_ARCHIVE,
    active: () => view.value === VIEWS.APP_ARCHIVE,
  }]
}, {
  label: t('appearance.title'),
  icon: 'fa fa-pen-ruler fa-fw',
  route: VIEWS.APPEARANCE,
  active: () => view.value === VIEWS.APPEARANCE,
  visible: () => profile.value.isAtLeastAdmin,
}, {
  label: t('system.title'),
  icon: 'fa fa-server fa-fw',
  visible: () => profile.value.isAtLeastAdmin,
  childItems: [{
    label: 'Docker',
    icon: 'fa-brands fa-fw fa-docker',
    route: VIEWS.DOCKER,
    active: () => view.value === VIEWS.DOCKER,
  }, {
    label: t('services.title'),
    icon: 'fa fa-diagram-project fa-fw',
    route: VIEWS.SERVICES,
    active: () => view.value === VIEWS.SERVICES,
  }, {
    label: t('eventlog.title'),
    icon: 'fa fa-list-alt fa-fw',
    route: VIEWS.SYSTEM_EVENTLOG,
    active: () => view.value === VIEWS.SYSTEM_EVENTLOG,
  }, {
    label: t('settings.updates.title'),
    icon: 'fa fa-fw fa-square-up-right',
    route: VIEWS.SYSTEM_UPDATE,
    active: () => view.value === VIEWS.SYSTEM_UPDATE,
  }, {
    label: t('system.settings.title'),
    icon: 'fa fa-fw fa-screwdriver-wrench',
    route: VIEWS.SYSTEM_SETTINGS,
    active: () => view.value === VIEWS.SYSTEM_SETTINGS,
  }]
}, {
  separator: true,
  visible: () => profile.value.isAtLeastAdmin,
}, {
  label: t('server.title'),
  icon: 'fa fa-fw fa-microchip',
  route: VIEWS.SERVER,
  active: () => view.value === VIEWS.SERVER,
  visible: () => profile.value.isAtLeastAdmin,
}, {
  label: t('settings.appstoreAccount.title'),
  icon: 'fa fa-fw fa-crown',
  route: VIEWS.CLOUDRON_ACCOUNT,
  active: () => view.value === VIEWS.CLOUDRON_ACCOUNT,
  visible: () => profile.value.isAtLeastOwner,
}]);

const offlineOverlay = useTemplateRef('offlineOverlay');

fetcher.globalOptions.errorHook = (error) => {
  // network error, request killed by browser
  if (error instanceof TypeError) {
    return offlineOverlay.value.open();
  }

  // re-login will make the code get a new token
  if (error.status === 401) return profileModel.logout();

  if (error.status === 500 || error.status === 501) {
    // actual internal server error, most likely a bug or timeout log to console only to not alert the user
    console.error(error);
    console.log('------\nCloudron Internal Error\n\nIf you see this, please send a mail with above log to support@cloudron.io\n------\n');
  }

  if (error.status >= 502) {
    // This means the box service is not reachable. We just show offline banner for now
    ready.value = false;
    return offlineOverlay.value.open();
  }
};

const dashboardModel = DashboardModel.create();
const profileModel = ProfileModel.create();
const provisionModel = ProvisionModel.create();
const notificationModel = NotificationsModel.create();

const inputDialog = useTemplateRef('inputDialog');
const subscriptionRequiredDialog = useTemplateRef('subscriptionRequiredDialog');
const ready = ref(false);
const view = ref('');
const profile = ref({});
const dashboardDomain = ref('');
const notificationCount = ref(0);
const subscription = ref({
  plan: {},
});
const config = ref({});
const avatarUrl = ref('');
const features = ref({});

function onHashChange() {
  const v = window.location.hash.split('?')[0];

  if (v === VIEWS.APPS) {
    view.value = VIEWS.APPS;
  } else if (v.indexOf(VIEWS.APPSTORE) === 0 && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.APPSTORE;
  } else if (v.indexOf(VIEWS.APP+'/') === 0) { // this checks permissions within the view as we may have an app operator
    view.value = VIEWS.APP;
  } else if (v === VIEWS.APPEARANCE && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.APPEARANCE;
  } else if (v === VIEWS.BACKUP_SITES && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.BACKUP_SITES;
  } else if (v === VIEWS.APP_ARCHIVE && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.APP_ARCHIVE;
  } else if (v === VIEWS.CLOUDRON_ACCOUNT && profile.value.isAtLeastOwner) {
    view.value = VIEWS.CLOUDRON_ACCOUNT;
  } else if (v === VIEWS.DOMAINS && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.DOMAINS;
  } else if (v.indexOf(VIEWS.EMAIL_DOMAIN+'/') === 0 && profile.value.isAtLeastMailManager) {
    view.value = VIEWS.EMAIL_DOMAIN;
  } else if (v === VIEWS.EMAIL_DOMAINS && profile.value.isAtLeastMailManager) {
    view.value = VIEWS.EMAIL_DOMAINS;
  } else if (v === VIEWS.MAILBOXES && profile.value.isAtLeastMailManager) {
    view.value = VIEWS.MAILBOXES;
  } else if (v === VIEWS.MAILINGLISTS && profile.value.isAtLeastMailManager) {
    view.value = VIEWS.MAILINGLISTS;
  } else if (v === VIEWS.EMAIL_SETTINGS && profile.value.isAtLeastMailManager) {
    view.value = VIEWS.EMAIL_SETTINGS;
  } else if (v === VIEWS.EMAIL_EVENTLOG && profile.value.isAtLeastMailManager) {
    view.value = VIEWS.EMAIL_EVENTLOG;
  } else if (v === VIEWS.SERVER && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.SERVER;
  } else if (v === VIEWS.NOTIFICATIONS && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.NOTIFICATIONS;
  } else if (v === VIEWS.NETWORK && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.NETWORK;
  } else if (v === VIEWS.PROFILE) {
    view.value = VIEWS.PROFILE;
  } else if (v === VIEWS.SERVICES && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.SERVICES;
  } else if (v === VIEWS.SYSTEM_SETTINGS && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.SYSTEM_SETTINGS;
  } else if (v === VIEWS.DOCKER && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.DOCKER;
  } else if (v === VIEWS.SYSTEM_EVENTLOG && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.SYSTEM_EVENTLOG;
  } else if (v === VIEWS.SYSTEM_UPDATE && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.SYSTEM_UPDATE;
  } else if (v === VIEWS.USER_DIRECTORY_SETTINGS && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.USER_DIRECTORY_SETTINGS;
  } else if (v === VIEWS.LDAP && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.LDAP;
  } else if (v === VIEWS.OPENID && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.OPENID;
  } else if (v === VIEWS.USERS && profile.value.isAtLeastUserManager) {
    view.value = VIEWS.USERS;
  } else if (v === VIEWS.GROUPS && profile.value.isAtLeastUserManager) {
    view.value = VIEWS.GROUPS;
  } else if (v === VIEWS.VOLUMES && profile.value.isAtLeastAdmin) {
    view.value = VIEWS.VOLUMES;
  } else {
    window.location.href = VIEWS.APPS;
  }
}

BrandingModel.onChange(BrandingModel.KEYS.NAME, (value) => {
  window.document.title = value;
  config.value.cloudronName = value;
});

BrandingModel.onChange(BrandingModel.KEYS.AVATAR, (value) => {
  avatarUrl.value = value;
  if (document.querySelector('link[rel="icon"]')) document.querySelector('link[rel="icon"]').href = value;
});

ProfileModel.onChange(ProfileModel.KEYS.AVATAR, (value) => {
  profile.value.avatarUrl = value;
});

async function refreshProfile() {
  const [error, result] = await profileModel.get();
  if (error) return window.cloudron.onError(error);
  profile.value = result;
}

async function refreshConfigAndFeatures() {
  const [error, result] = await dashboardModel.config();
  if (error) return window.cloudron.onError(error);

  const currentVersion = localStorage.getItem('version');
  if (currentVersion === null) {
    localStorage.setItem('version', result.version);
  } else if (result.version !== currentVersion) {
    console.log('Dashboard version changed, reloading');
    localStorage.setItem('version', result.version);
    window.location.reload(true);

    // return never ending promise to just wait for the reload
    return new Promise(() => {});
  }

  config.value = result;
  features.value = result.features;
  dashboardDomain.value = result.adminDomain;
}

async function refreshNotifications() {
  const [error, result] = await notificationModel.list(false);
  if (error) return console.error(error);
  notificationCount.value = result.length;
}

async function onOnline() {
  ready.value = true;
  await refreshConfigAndFeatures(); // reload dashboard if needed after an update
}

const isMobile = ref(window.innerWidth <= 576);
function checkForMobile() {
  isMobile.value = window.innerWidth <= 576;
}

provide('subscriptionRequiredDialog', subscriptionRequiredDialog);
provide('features', features);
provide('profile', profile);
provide('refreshProfile', refreshProfile);
provide('refreshFeatures', refreshConfigAndFeatures);
provide('refreshNotifications', refreshNotifications);
provide('dashboardDomain', dashboardDomain);
provide('isMobile', isMobile);
provide('inputDialog', inputDialog);

onMounted(async () => {
  window.addEventListener('resize', checkForMobile);

  const [error, result] = await provisionModel.status();
  if (error) return window.cloudron.onError(error);

  if (redirectIfNeeded(result, 'dashboard')) return; // redirected to some other view...

  if (!localStorage.token) {
    localStorage.setItem('redirectToHash', window.location.hash);

    const clientId = API_ORIGIN ? TOKEN_TYPES.ID_DEVELOPMENT : TOKEN_TYPES.ID_WEBADMIN;
    window.location.href = await startAuthFlow(clientId, API_ORIGIN);

    return;
  }

  await refreshConfigAndFeatures();
  await refreshProfile();

  // ensure language from profile if set
  if (profile.value.language) await setLanguage(profile.value.language, true);

  avatarUrl.value = `https://${config.value.adminFqdn}/api/v1/cloudron/avatar`;

  window.addEventListener('hashchange', onHashChange);
  onHashChange();

  console.log(`Cloudron dashboard v${config.value.version}`);

  if (profile.value.isAtLeastAdmin) refreshNotifications();

  ready.value = true;

  // when done, redirect the user to setup 2fa if it is mandatory and neither totp nor passkey is setup
  if (config.value.mandatory2FA && !profile.value.totpEnabled && !profile.value.hasPasskey) {
    return window.location.href = VIEWS.PROFILE;
  }
});

onUnmounted(() => {
  window.removeEventListener('resize', checkForMobile);
});

</script>

<template>
  <div style="overflow: hidden; height: 100%;">
    <Notification />
    <OfflineOverlay ref="offlineOverlay" @online="onOnline()" :href="'https://docs.cloudron.io/troubleshooting/'" :label="$t('main.offline')" />
    <SubscriptionRequiredDialog ref="subscriptionRequiredDialog"/>
    <RequestErrorDialog/>
    <InputDialog ref="inputDialog"/>

    <div v-if="ready" style="display: flex; flex-direction: row; overflow: hidden; height: 100%;">
      <SideBar v-if="profile.isAtLeastUserManager" :items="menuItems" :cloudron-name="config.cloudronName" :cloudron-avatar-url="avatarUrl"/>

      <div style="flex-grow: 1; display: flex; flex-direction: column; overflow: hidden; height: 100%;">
        <Headerbar :config="config" :subscription="subscription" :notification-count="notificationCount"/>

        <div style="display: flex; justify-content: center; overflow: auto; flex-grow: 1; padding: 0; margin: 0 10px; position: relative;">
          <KeepAlive>
            <AppsView v-if="view === VIEWS.APPS" />
            <AppstoreView v-else-if="view === VIEWS.APPSTORE" />
          </KeepAlive>
          <AppConfigureView v-if="view === VIEWS.APP" />
          <AppearanceView v-else-if="view === VIEWS.APPEARANCE" />
          <BackupSitesView v-else-if="view === VIEWS.BACKUP_SITES" />
          <AppArchiveView v-else-if="view === VIEWS.APP_ARCHIVE" />
          <CloudronAccountView v-else-if="view === VIEWS.CLOUDRON_ACCOUNT" />
          <DomainsView v-else-if="view === VIEWS.DOMAINS" />
          <EmailDomainsView v-else-if="view === VIEWS.EMAIL_DOMAINS" />
          <EmailDomainView v-else-if="view === VIEWS.EMAIL_DOMAIN" />
          <EmailMailboxesView v-else-if="view === VIEWS.MAILBOXES" />
          <EmailMailinglistsView v-else-if="view === VIEWS.MAILINGLISTS" />
          <EmailSettingsView v-else-if="view === VIEWS.EMAIL_SETTINGS" />
          <EmailEventlogView v-else-if="view === VIEWS.EMAIL_EVENTLOG" />
          <EventlogView v-else-if="view === VIEWS.SYSTEM_EVENTLOG" />
          <ServerView v-else-if="view === VIEWS.SERVER" />
          <NetworkView v-else-if="view === VIEWS.NETWORK" />
          <NotificationsView v-else-if="view === VIEWS.NOTIFICATIONS" />
          <ProfileView v-else-if="view === VIEWS.PROFILE" />
          <ServicesView v-else-if="view === VIEWS.SERVICES" />
          <SystemSettingsView v-else-if="view === VIEWS.SYSTEM_SETTINGS" />
          <DockerView v-else-if="view === VIEWS.DOCKER" />
          <SystemUpdateView v-else-if="view === VIEWS.SYSTEM_UPDATE" />
          <UserDirectorySettingsView v-else-if="view === VIEWS.USER_DIRECTORY_SETTINGS" />
          <LdapView v-else-if="view === VIEWS.LDAP" />
          <OpenIdView v-else-if="view === VIEWS.OPENID" />
          <UsersView v-else-if="view === VIEWS.USERS" />
          <GroupsView v-else-if="view === VIEWS.GROUPS" />
          <VolumesView v-else-if="view === VIEWS.VOLUMES" />
        </div>
      </div>
    </div>
  </div>
</template>
