<script setup>

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

import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import { Button, ButtonGroup } from 'pankow';
import Access from '../components/app/Access.vue';
import Backups from '../components/app/Backups.vue';
import Cron from '../components/app/Cron.vue';
import Display from '../components/app/Display.vue';
import Email from '../components/app/Email.vue';
import Eventlog from '../components/app/Eventlog.vue';
import Graphs from '../components/app/Graphs.vue';
import Info from '../components/app/Info.vue';
import Location from '../components/app/Location.vue';
import Proxy from '../components/app/Proxy.vue';
import Resources from '../components/app/Resources.vue';
import Repair from '../components/app/Repair.vue';
import Security from '../components/app/Security.vue';
import Services from '../components/app/Services.vue';
import Storage from '../components/app/Storage.vue';
import Uninstall from '../components/app/Uninstall.vue';
import Updates from '../components/app/Updates.vue';
import AppsModel from '../models/AppsModel.js';
import TasksModel from '../models/TasksModel.js';
import { API_ORIGIN, APP_TYPES, ISTATES, RSTATES, HSTATES } from '../constants.js';

const appsModel = AppsModel.create();
const tasksModel = TasksModel.create();
const installationStateLabel = AppsModel.installationStateLabel;

const busy = ref(true);
const id = ref('');
const app = ref({});
const view = ref('');
const link = ref('');
const infoMenu = ref([]);
const hasLocalStorage = ref(false);
const hasOptionalServices = ref(false);
const hasEmail = ref(false);
const busyStopTask = ref(false);

const isAppStopped = computed(() => {
  return appsModel.isStopped(app.value);
});

function onSetView(newView) {
  view.value = newView;
  window.location.hash = `/app/${id.value}/${newView}`;
}

async function onToggleRunState() {
  if (isAppStopped.value) {
    const [error] = await appsModel.start(app.value.id);
    if (error) return console.error(error);
  } else {
    const [error] = await appsModel.stop(app.value.id);
    if (error) return console.error(error);
  }
}

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

  app.value = result;

  link.value = (result.installationState !== ISTATES.INSTALLED || result.health !== HSTATES.HEALTHY || result.runState === RSTATES.STOPPED) ? '' : `https://${result.fqdn}`;
  hasLocalStorage.value = result.manifest && result.manifest.addons && result.manifest.addons.localstorage;
  hasOptionalServices.value = result.manifest && result.manifest.addons && (result.manifest.addons.turn?.optional || result.manifest.addons.redis?.optional);
  hasEmail.value = result.manifest && result.manifest.addons && (result.manifest.addons.sendmail || result.manifest.addons.recvmail);

  // TODO info menu will likely not change during polling
  infoMenu.value = [];
  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; }
  });

  refreshTimer = setTimeout(refresh, 2000);
}

async function onStopAppTask() {
  if (!app.value.taskId) return;

  busyStopTask.value = true;

  const [error] = await tasksModel.stop(app.value.taskId);
  if (error) console.error(error);

  busyStopTask.value = false;
}

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

  onSetView(parts[1] || 'info');

  busy.value = false;
});

onBeforeUnmount(() => {
  if (refreshTimer) clearTimeout(refreshTimer);
});

</script>

<template>
  <div class="configure-outer">
    <div class="configure-inner" v-if="!busy">
      <div class="titlebar">
        <div style="display: flex; flex-grow: 1;">
          <img :src="app.iconUrl" v-fallback-image="API_ORIGIN + '/img/appicon_fallback.png'" style="height: 64px; width: 64px; margin-right: 10px;"/>
          <h2>
            <a class="applink" :href="link || null" target="_blank">{{ app.label || app.fqdn }}</a>
            <div class="statelabel">
              {{ installationStateLabel(app) }} {{ app.message ? ' - ' + app.message : '' }}
            </div>
          </h2>
        </div>

        <div style="display: flex; gap: 10px; align-items: center;">
          <Button v-if="app.taskId" danger tool plain icon="fa-solid fa-xmark" v-tooltip="'Cancel Task'" :loading="busyStopTask" :disabled="busyStopTask" @click="onStopAppTask()"/>
          <Button secondary tool
            @click="onToggleRunState()"
            :disabled="app.taskId || app.error || app.installationState === 'pending_start' || app.installationState === 'pending_stop'"
            v-tooltip="$t(isAppStopped ? 'app.uninstall.startStop.startAction' : 'app.uninstall.startStop.stopAction')"
            :loading="app.installationState === 'pending_start' || app.installationState === 'pending_stop'"
            :icon="isAppStopped ? 'fa-solid fa-play' : 'fa-solid fa-power-off'"
          />
          <ButtonGroup>
            <Button secondary tool :href="`/logs.html?appId=${app.id}`" target="_blank" v-tooltip="$t('app.logsActionTooltip')" icon="fa-solid fa-align-left" />
            <Button secondary 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 secondary tool v-if="hasLocalStorage" :href="`/filemanager.html#/home/app/${app.id}`" target="_blank" v-tooltip="$t('app.filemanagerActionTooltip')" icon="fas fa-folder" />
          </ButtonGroup>

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

      <div class="apptask-progress">
        <div class="apptask-progress-filled" :style="{ width: app.progress+'%' }"></div>
      </div>

      <div class="configure-body">
        <div class="configure-menu">
          <div class="configure-menu-item" @click="onSetView('info')" :active="view === 'info' ? true : null">{{ $t('app.infoTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('display')" :active="view === 'display' ? true : null">{{ $t('app.displayTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('location')" :active="view === 'location' ? true : null" v-if="app.accessLevel === 'admin'">{{ $t('app.locationTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('proxy')" :active="view === 'proxy' ? true : null" v-if="app.type === APP_TYPES.PROXIED">Proxy</div>
          <div class="configure-menu-item" @click="onSetView('access')" :active="view === 'access' ? true : null" v-if="app.accessLevel === 'admin'">{{ $t('app.accessControlTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('resources')" :active="view === 'resources' ? true : null" v-if="app.type !== APP_TYPES.PROXIED">{{ $t('app.resourcesTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('services')" :active="view === 'services' ? true : null" v-if="app.type !== APP_TYPES.PROXIED && hasOptionalServices">{{ $t('app.servicesTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('storage')" :active="view === 'storage' ? true : null" v-if="app.accessLevel === 'admin' && app.type !== APP_TYPES.PROXIED">{{ $t('app.storageTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('graphs')" :active="view === 'graphs' ? true : null" v-if="app.type !== APP_TYPES.PROXIED">{{ $t('app.graphsTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('security')" :active="view === 'security' ? true : null">{{ $t('app.securityTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('email')" :active="view === 'email' ? true : null" v-if="app.accessLevel === 'admin' && hasEmail && app.type !== APP_TYPES.PROXIED">{{ $t('app.emailTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('cron')" :active="view === 'cron' ? true : null" v-if="app.type !== APP_TYPES.PROXIED">{{ $t('app.cronTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('updates')" :active="view === 'updates' ? true : null">{{ $t('app.updatesTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('backups')" :active="view === 'backups' ? true : null" v-if="app.type !== APP_TYPES.PROXIED">{{ $t('app.backupsTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('repair')" :active="view === 'repair' ? true : null">{{ $t('app.repairTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('eventlog')" :active="view === 'eventlog' ? true : null">{{ $t('app.eventlogTabTitle') }}</div>
          <div class="configure-menu-item" @click="onSetView('uninstall')" :active="view === 'uninstall' ? true : null" v-if="app.accessLevel === 'admin'">{{ $t('app.uninstallTabTitle') }}</div>
        </div>
        <div class="configure-content">
          <Transition name="slide-fade" mode="out-in">
            <Info v-if="view === 'info'" :app="app"/>
            <Display v-else-if="view === 'display'" :app="app"/>
            <Location v-else-if="view === 'location'" :app="app"/>
            <Proxy v-else-if="view === 'proxy'" :app="app"/>
            <Access v-else-if="view === 'access'" :app="app"/>
            <Resources v-else-if="view === 'resources'" :app="app"/>
            <Services v-else-if="view === 'services'" :app="app"/>
            <Storage v-else-if="view === 'storage'" :app="app"/>
            <Graphs v-else-if="view === 'graphs'" :app="app"/>
            <Security v-else-if="view === 'security'" :app="app"/>
            <Email v-else-if="view === 'email'" :app="app"/>
            <Cron v-else-if="view === 'cron'" :app="app"/>
            <Updates v-else-if="view === 'updates'" :app="app"/>
            <Backups v-else-if="view === 'backups'" :app="app"/>
            <Repair v-else-if="view === 'repair'" :app="app"/>
            <Eventlog v-else-if="view === 'eventlog'" :app="app"/>
            <Uninstall v-else-if="view === 'uninstall'" :app="app"/>
          </Transition>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

.slide-fade-enter-active {
  transition: all 0.2s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}

.applink {
  display: flex;
  align-items: center;
  color: var(--pankow-text-color);
}

.titlebar h2 {
  flex-grow: 1;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.statelabel {
  font-size: 12px;
  margin-top: 6px;
}

.applink:not([href]) {
  cursor: not-allowed;
}

.configure-outer {
  width: 100%;
  margin: auto;
}

.configure-inner {
  width: 100%;
  max-width: 1200px;
  margin: auto;
  padding-right: 15px;
}

.titlebar {
  display: flex;
  justify-content: space-between;
}

.apptask-progress {
  position: relative;
  width: 100%;
  height: 5px;
  text-align: center;
  border-radius: 10px;
  color: var(--pankow-text-color);
}

.apptask-progress-filled {
  background-color: var(--pankow-color-primary);
  position: relative;
  top: 0;
  left: 0;
  height: 100%;
  border-radius: 10px;
  z-index: 1;
  background-image: linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);
  background-size: 40px 40px;
  animation: apptask-progress-bar-stripes 1s linear infinite;
  transition: width 300ms;
}

@keyframes apptask-progress-bar-stripes {
  from {
    background-position: 40px 0;
  }
  to {
    background-position: 0 0;
  }
}

.configure-body {
  margin-top: 20px;
  margin-bottom: 10px;
  display: flex;
}

.configure-menu-item {
  white-space: nowrap;
  cursor: pointer;
  padding: 4px 60px 4px 4px;
}

.configure-menu-item[active] {
  color: var(--pankow-color-primary-active);
  font-weight: bold;
}

.configure-menu-item:hover {
  color: var(--pankow-color-primary-hover);
}

.configure-content {
  flex-grow: 1;
}

</style>
