<script setup>

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

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

import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, ButtonGroup, TabView } from 'pankow';
import Info from '../components/app/Info.vue';
import AppsModel from '../models/AppsModel.js';
import { APP_TYPES } from '../constants.js';

const appsModel = AppsModel.create();

const tabView = useTemplateRef('tabView');
const tabs = ref({
  info: t('app.infoTabTitle'),
  display: t('app.displayTabTitle'),
  location: t('app.locationTabTitle'),
  proxy: 'Proxy',
  access: t('app.accessControlTabTitle'),
  resources: t('app.resourcesTabTitle'),
  services: t('app.servicesTabTitle'),
  storage: t('app.storageTabTitle'),
  graphs: t('app.graphsTabTitle'),
  security: t('app.securityTabTitle'),
  email: t('app.emailTabTitle'),
  cron: t('app.cronTabTitle'),
  updates: t('app.updatesTabTitle'),
  backups: t('app.backupsTabTitle'),
  repair: t('app.repairTabTitle'),
  eventlog: t('app.eventlogTabTitle'),
  uninstall: t('app.uninstallTabTitle'),
});
const id = ref('');
const app = ref({});
const link = ref('');
const infoMenu = ref([]);
const hasLocalStorage = ref(false);

async function refresh() {
  const [error, result] = await appsModel.get(id.value);
  if (error) return console.error(error);

  app.value = result;

  // app links have http already in the fqdn
  link.value = result.fqdn.indexOf('http') !== 0 ? 'https://' + result.fqdn : result.fqdn;
  hasLocalStorage.value = result.manifest && result.manifest.addons && result.manifest.addons.localstorage;

  infoMenu.value.push({
    label: t('app.docsAction'),
    disabled: !result.manifest?.documentationUrl,
    // TODO support real href links
    action: () => { window.location.href = result.manifest.documentationUrl; }
  });

  if (result.manifest?.postInstallMessage) {
    infoMenu.value.push({
      label: t('app.firstTimeSetupAction'),
      // TODO action
    });
  }

  if (result.manifest?.configurePath) {
    infoMenu.value.push({
      label: t('app.adminPageAction'),
      // TODO support real href links
      action: () => { window.location.href = link.value + result.manifest.configurePath; }
    });
  }

  if (result.manifest?.addons?.localstorage?.ftp) {
    infoMenu.value.push({
      label: t('app.sftpInfoAction'),
      // TODO action
    });
  }

  infoMenu.value.push({ separator: true });
  infoMenu.value.push({
    label: t('app.forumUrlAction'),
    disabled: !result.manifest?.forumUrl,
    // TODO support real href links
    action: () => { window.location.href = result.manifest.forumUrl; }
  });
  infoMenu.value.push({ separator: true });
  infoMenu.value.push({
    label: t('app.projectWebsiteAction'),
    disabled: !result.manifest?.website,
    // TODO support real href links
    action: () => { window.location.href = result.manifest.website; }
  });
}

onMounted(async () => {
  const tmp = window.location.hash.slice('#/app/'.length);
  if (!tmp) return;

  const parts = tmp.split('/');
  if (parts.length !== 2) return;

  id.value = parts[0];

  await refresh();

  tabView.value.open(parts[1] || 'info');
});

</script>

<template>
  <div class="content">
    <div style="display: flex; margin-bottom: 20px; justify-content: space-between;">
      <div style="display: flex;">
        <img :src="API_ORIGIN + app.iconUrl" v-fallback-image="API_ORIGIN + '/img/appicon_fallback.png'" style="width: 64px"/>
        <h2>{{ app.label || app.fqdn }}</h2>
      </div>

      <div style="display: flex; gap: 10px; align-items: center;">
        <Button outline tool
          @click="onToggleRunState()"
          :disabled="app.taskId || app.error || app.installationState === 'pending_start' || app.installationState === 'pending_stop'"
          v-tooltip="$t(app.runState === 'stopped' ? 'app.uninstall.startStop.startAction' : 'app.uninstall.startStop.stopAction')"
          :loading="app.installationState === 'pending_start' || app.installationState === 'pending_stop'"
          :icon="app.installationState === 'pending_start' || app.installationState === 'pending_stop' ? '' : (app.runState === 'stopped' ? 'fa-solid fa-play' : 'fa-solid fa-power-off')"
        />
        <ButtonGroup>
          <Button outline tool :href="`/logs.html?appId=${app.id}`" target="_blank" v-tooltip="$t('app.logsActionTooltip')" icon="fa-solid fa-align-left" />
          <Button outline tool v-if="app.type !== APP_TYPES.PROXIED" :href="`/terminal.html?id=${app.id}`" target="_blank" v-tooltip="$t('app.terminalActionTooltip')" icon="fa fa-terminal" />
          <Button outline tool v-if="hasLocalStorage" :href="`/filemanager.html#/home/app/${app.id}`" target="_blank" v-tooltip="$t('app.filemanagerActionTooltip')" icon="fas fa-folder" />
        </ButtonGroup>

        <Button outline tool icon="fa-solid fa-book" v-tooltip="$t('app.docsActionTooltip')" :menu="infoMenu" />
      </div>
    </div>

    <TabView ref="tabView" :tabs="tabs">
      <template #info><Info :app="app"/></template>
      <template #display>Display</template>
      <template #location></template>
      <template #proxy></template>
      <template #access></template>
      <template #resources></template>
      <template #services></template>
      <template #storage></template>
      <template #graphs></template>
      <template #security></template>
      <template #email></template>
      <template #cron></template>
      <template #updates></template>
      <template #backups></template>
      <template #repair></template>
      <template #eventlog></template>
      <template #uninstall></template>
    </TabView>
  </div>
</template>
