<script>

import { Notification } from 'pankow';

import AppsView from './AppsView.vue';
import AppstoreView from './AppstoreView.vue';
import ProfileView from './ProfileView.vue';
import ServicesView from '../views/ServicesView.vue';
import SupportView from './SupportView.vue';
import UserDirectoryView from './UserDirectoryView.vue';
import VolumesView from './VolumesView.vue';

import ProfileModel from '../models/ProfileModel.js';

const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;

const VIEWS = {
  APPS: 'apps',
  APPSTORE: 'appstore',
  PROFILE: 'profile',
  SUPPORT: 'support',
  SERVICES: 'services',
  USER_DIRECTORY: 'user-directory',
  VOLUMES: 'volumes',
};

export default {
  name: 'Index',
  components: {
    AppsView,
    AppstoreView,
    Notification,
    ProfileView,
    SupportView,
    ServicesView,
    UserDirectoryView,
    VolumesView,
  },
  data() {
    return {
      VIEWS,
      accessToken: localStorage.token,
      profile: {},
      view: ''
    };
  },
  methods: {
  },
  async mounted() {
    if (!localStorage.token) {
      console.error('Set localStorage.token');
      return;
    }

    const profileModel = ProfileModel.create(API_ORIGIN, localStorage.token);
    this.profile = await profileModel.get();

    const that = this;
    function onHashChange() {
      const view = location.hash.slice(2);

      if (view === VIEWS.APPS) {
        that.view = VIEWS.APPS;
      } else if (view.indexOf(VIEWS.APPSTORE) === 0) {
        that.view = VIEWS.APPSTORE;
      } else if (view === VIEWS.PROFILE) {
        that.view = VIEWS.PROFILE;
      } else if (view === VIEWS.SERVICES) {
        that.view = VIEWS.SERVICES;
      } else if (view === VIEWS.SUPPORT) {
        that.view = VIEWS.SUPPORT;
      }  else if (view === VIEWS.USER_DIRECTORY) {
        that.view = VIEWS.USER_DIRECTORY;
      } else if (view === VIEWS.VOLUMES) {
        that.view = VIEWS.VOLUMES;
      } else {
        that.view = '';
      }

      // hack for layout to avoid consuming space if vue view is not active
      document.getElementById('app').style.height = that.view ? 'auto' : '0';
    }

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

</script>

<template>
  <div>
    <Notification />

    <TransitionGroup name="grid-animation">
      <AppsView v-if="view === VIEWS.APPS" />
      <AppstoreView v-else-if="view === VIEWS.APPSTORE" />
      <ProfileView v-else-if="view === VIEWS.PROFILE" />
      <ServicesView v-else-if="view === VIEWS.SERVICES" />
      <SupportView v-else-if="view === VIEWS.SUPPORT" />
      <UserDirectoryView v-else-if="view === VIEWS.USER_DIRECTORY" />
      <VolumesView v-else-if="view === VIEWS.VOLUMES" />
    </TransitionGroup>
  </div>
</template>
