<script setup>

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

import { ref, computed, useTemplateRef, onMounted, onUnmounted, inject } from 'vue';
import { Button, Menu, SingleSelect, Icon, TableView, TextInput, ProgressBar } from '@cloudron/pankow';
import { API_ORIGIN, APP_TYPES, HSTATES, ISTATES, RSTATES } from '../constants.js';
import AppsModel from '../models/AppsModel.js';
import ApplinksModel from '../models/ApplinksModel.js';
import DomainsModel from '../models/DomainsModel.js';
import ApplinkDialog from '../components/ApplinkDialog.vue';
import PostInstallDialog from '../components/PostInstallDialog.vue';

const appsModel = AppsModel.create();
const domainsModel = DomainsModel.create();
const applinksModel = ApplinksModel.create();

const VIEW_TYPE = {
  LIST: 'list',
  GRID: 'grid',
};

let refreshInterval;

const ready = ref(false);
const filter = ref('');
const profile = inject('profile');
const apps = ref([]);
const viewType = ref((localStorage.appsView && (localStorage.appsView === VIEW_TYPE.GRID || localStorage.appsView === VIEW_TYPE.LIST)) ? localStorage.appsView : VIEW_TYPE.GRID);
const tagFilter = ref('');
const tagFilterOptions = ref([{
  id: '',
  name: 'All Tags',
}]);
const domainFilter = ref('');
const domainFilterOptions = ref([{
  id: '',
  domain: 'All Domains',
}]);
const stateFilter = ref('');
const stateFilterOptions = [
  { id: '', label: 'All States' },
  { id: 'running', label: 'Running' },
  { id: 'stopped', label: 'Stopped' },
  { id: 'update_available', label: 'Update Available' },
  { id: 'not_responding', label: 'Not Responding' },
];
const listColumns = {
  icon: {
    width: '32px'
  },
  label: {
    label: 'Label',
    sort: (a, b, fullA, fullB) => {
      if (!fullA || !fullA) return -1;
      const checkA = fullA.label || fullA.subdomain || fullA.fqdn;
      const checkB = fullB.label || fullB.subdomain || fullB.fqdn;
      return checkA < checkB ? -1 : (checkA > checkB ? 1 : 0);
    },
  },
  fqdn: {
    label: 'Location',
    sort: true,
    hideMobile: true,
  },
  status: {
    label: 'Status',
    hideMobile: true,
    sort: (a, b, fullA, fullB) => {
      if (!fullA || !fullA) return -1;
      const checkA = fullA.installationState + '-' + fullA.runState + '-' + fullA.health;
      const checkB = fullB.installationState + '-' + fullB.runState + '-' + fullB.health;
      return checkA < checkB ? -1 : (checkA > checkB ? 1 : 0);
    },
  },
  appTitle: {
    label: 'App Title',
    hideMobile: true,
    sort: (a, b, fullA, fullB) => {
      if (!fullA || !fullA) return -1;
      const checkA = fullA.manifest.title;
      const checkB = fullB.manifest.title;
      return checkA < checkB ? -1 : (checkA > checkB ? 1 : 0);
    },
  },
  sso: {
    label: 'Login',
    hideMobile: true,
    sort: (a, b, fullA, fullB) => {
      if (!fullA || !fullA) return -1;

      const checkA = fullA.type === APP_TYPES.LINK ? 0 : (fullA.ssoAuth && fullA.manifest.addons.oidc ? 1 : (fullA.ssoAuth && (!fullA.manifest.addons.oidc && !fullA.manifest.addons.email) ? 2 : (!fullA.ssoAuth && !fullA.manifest.addons.email ? 3 : 4)));
      const checkB = fullB.type === APP_TYPES.LINK ? 0 : (fullB.ssoAuth && fullB.manifest.addons.oidc ? 1 : (fullB.ssoAuth && (!fullB.manifest.addons.oidc && !fullB.manifest.addons.email) ? 2 : (!fullB.ssoAuth && !fullB.manifest.addons.email ? 3 : 4)));

      return checkA - checkB;
    },
  },
  checklist: {},
  actions: {}
};

const actionMenuModel = ref([]);
const actionMenuElement = useTemplateRef('actionMenuElement');
function onActionMenu(app, event) {
  actionMenuModel.value = [{
    icon: 'fa-solid fa-arrow-up',
    label: t('app.updateAvailableTooltip'),
    visible: !!app.updateInfo,
    href: `#/app/${app.id}/updates`,
  }, {
    separator: true,
    visible: !!app.updateInfo,
  }, {
    icon: 'fa-solid fa-align-left',
    label: t('app.logsActionTooltip'),
    visible: app.type !== APP_TYPES.LINK,
    target: '_blank',
    href: '/logs.html?appId=' + app.id,
  }, {
    icon: 'fa-solid fa-terminal',
    label: t('app.terminalActionTooltip'),
    visible: app.type !== APP_TYPES.PROXIED && app.type !== APP_TYPES.LINK,
    target: '_blank',
    href: '/terminal.html?id=' + app.id,
  }, {
    icon: 'fa-solid fa-folder',
    label: t('app.filemanagerActionTooltip'),
    visible: !!app.manifest?.addons?.localstorage,
    target: '_blank',
    href: '/filemanager.html#/home/app/' + app.id,
  }, {
    icon: 'fa-solid fa-cog',
    label: t('app.configureTooltip'),
    href: `#/app/${app.id}/info`,
  }];

  actionMenuElement.value.open(event, event.currentTarget);
}

const filteredApps = computed(() => {
  return apps.value.filter(a => {
    return a.fqdn.indexOf(filter.value) !== -1;
  }).filter(a => {
    if (!domainFilter.value) return true;
    return a.domain === domainFilter.value;
  }).filter(a => {
    if (!tagFilter.value) return true;
    return a.tags.indexOf(tagFilter.value) !== -1;
  }).filter(a => {
    if (!stateFilter.value) return true;

    if (stateFilter.value === 'running') return a.runState === RSTATES.RUNNING && a.health === HSTATES.HEALTHY && a.installationState === ISTATES.INSTALLED;
    if (stateFilter.value === 'stopped') return a.runState === RSTATES.STOPPED;
    if (stateFilter.value === 'update_available') return a.updateInfo;

    return a.runState === RSTATES.RUNNING && (a.health !== HSTATES.HEALTHY || a.installationState !== ISTATES.INSTALLED); // not responding
  });
});

const applinkDialog = useTemplateRef('applinkDialog');
const postInstallDialog = useTemplateRef('postInstallDialog');

// hook for applinks otherwise it is a link
function openAppEdit(app, event) {
  if (app.type === APP_TYPES.LINK) {
    applinkDialog.value.open(app);
    event.preventDefault();
  }

  event.stopPropagation();
}

function onOpenApp(app, event) {
  function stopEvent() {
    event.stopPropagation();
    event.preventDefault();
  }

  if (app.installationState !== ISTATES.INSTALLED) {
    if (app.installationState === ISTATES.ERROR && isOperator(app)) window.location.href = `#/app/${app.id}/repair`;
    return stopEvent();
  }

  // app.health can also be null to indicate insufficient data
  if (!app.health) return stopEvent();
  if (app.runState === RSTATES.STOPPED) return stopEvent();

  if (app.health === HSTATES.UNHEALTHY || app.health === HSTATES.ERROR || app.health === HSTATES.DEAD) {
    if (isOperator(app)) window.location.href = `#/app/${app.id}/repair`;
    return stopEvent();
  }

  if (localStorage['confirmPostInstall_' + app.id]) {
    postInstallDialog.value.open(app, true);
    return stopEvent();
  }
}

function isOperator(app) {
  return app.accessLevel === 'operator' || app.accessLevel === 'admin';
}

async function refreshApps() {
  const [error, result] = await appsModel.list();
  if (error) return console.error(error);

  const [applinkError, applinks] = await applinksModel.list();
  if (applinkError) return console.error(applinkError);

  // amend properties to mimick full app
  for (const applink of applinks) {
    applink.type = APP_TYPES.LINK;
    applink.fqdn = applink.upstreamUri.replace('https://', '');
    applink.manifest = { addons: {}};
    applink.installationState = ISTATES.INSTALLED;
    applink.runState = RSTATES.RUNNING;
    applink.health = HSTATES.HEALTHY;
    applink.iconUrl = `${API_ORIGIN}/api/v1/applinks/${applink.id}/icon?access_token=${localStorage.token}&ts=${applink.ts}`;
    applink.accessLevel = profile.value.isAtLeastAdmin ? 'admin' : 'user';

    result.push(applink);
  }

  apps.value = result;

  // gets all tags used by all apps, flattens the arrays and new Set() will dedupe
  const tags = [...new Set(apps.value.map(a => a.tags).flat())].map(t => { return { id: t, name: t }; });
  tagFilterOptions.value = [{ id: '', name: 'All Tags', }].concat(tags);
}

function toggleView() {
  viewType.value = viewType.value === VIEW_TYPE.LIST ? VIEW_TYPE.GRID : VIEW_TYPE.LIST;
  localStorage.appsView = viewType.value;
}

onMounted(async () => {
  await refreshApps();

  const [error, result] = await domainsModel.list();
  if (error) return console.error(error);

  domainFilterOptions.value = domainFilterOptions.value.concat(result.map(d => { d.id = d.domain; return d; }));
  domainFilter.value = domainFilterOptions.value[0].id;

  stateFilter.value = stateFilterOptions[0].id;
  tagFilter.value = tagFilterOptions.value[0].id;

  ready.value = true;

  refreshInterval = setInterval(refreshApps, 5000);
});

onUnmounted(() => {
  clearInterval(refreshInterval);
});

</script>

<template>
  <div class="content">
    <Menu ref="actionMenuElement" :model="actionMenuModel" />
    <ApplinkDialog ref="applinkDialog" @success="refreshApps"/>
    <PostInstallDialog ref="postInstallDialog"/>

    <h1 class="view-header">
      {{ $t('apps.title') }}
      <div style="display: flex; gap: 4px; flex-wrap: wrap; margin-top: 10px;">
        <TextInput v-model="filter" :placeholder="$t('apps.searchPlaceholder')" />
        <SingleSelect class="pankow-no-mobile" v-if="profile.isAtLeastAdmin" :options="tagFilterOptions" option-key="id" option-label="name" v-model="tagFilter" />
        <SingleSelect class="pankow-no-mobile" v-if="profile.isAtLeastAdmin" :options="stateFilterOptions" option-key="id" v-model="stateFilter" />
        <SingleSelect class="pankow-no-mobile" v-if="profile.isAtLeastAdmin" :options="domainFilterOptions" option-key="id" option-label="domain" v-model="domainFilter" />
        <Button tool outline secondary @click="toggleView()" :icon="viewType === VIEW_TYPE.GRID ? 'fas fa-list' : 'fas fa-grip'"></Button>
      </div>
    </h1>

    <div v-if="!ready">
      <ProgressBar mode="indeterminate" :show-label="false" :slim="true"/>
    </div>
    <div v-else>
      <TransitionGroup name="grid-animation" tag="div" class="grid" v-if="viewType === VIEW_TYPE.GRID">
        <a v-for="app in filteredApps" :key="app.id" class="grid-item" @click="onOpenApp(app, $event)" :href="'https://' + app.fqdn" target="_blank">
          <img :alt="app.label || app.subdomain || app.fqdn" :src="app.iconUrl" v-fallback-image="API_ORIGIN + '/img/appicon_fallback.png'"/>
          <div class="grid-item-label" v-fit-text>{{ app.label || app.subdomain || app.fqdn }}</div>
          <div class="grid-item-task-label">{{ AppsModel.installationStateLabel(app) }}</div>

          <ProgressBar v-if="app.progress && isOperator(app)" :busy="true" :value="Math.max(10, app.progress)" :show-label="false" class="apps-progress"/>

          <a class="config" v-show="isOperator(app)" @click="openAppEdit(app, $event)" :href="`#/app/${app.id}/info`" :title="$t('app.configureTooltip')"><Icon icon="fa-solid fa-cog" /></a>
          <div class="grid-item-indictors">
            <a class="grid-item-update-indicator" v-if="app.updateInfo" @click.stop :href="isOperator(app) ? `#/app/${app.id}/updates` : null" v-tooltip="$t('app.updateAvailableTooltip')"><i class="fa-fw fa-solid fa-arrow-up"/></a>
            <a class="grid-item-checklist-indicator" v-if="AppsModel.pendingChecklistItems(app)" @click.stop :href="isOperator(app) ? `#/app/${app.id}/info` : null"><Icon icon="fa-solid fa-triangle-exclamation"/></a>
        </div>
        </a>
      </TransitionGroup>

      <div class="list" v-if="viewType === VIEW_TYPE.LIST">

        <TableView :columns="listColumns" :model="filteredApps">
          <template #icon="app">
            <a :href="'https://' + app.fqdn" target="_blank">
              <img :alt="app.label || app.subdomain || app.fqdn" class="list-icon" :src="app.iconUrl" v-fallback-image="API_ORIGIN + '/img/appicon_fallback.png'"/>
            </a>
          </template>
          <template #label="app">
            <a :href="'https://' + app.fqdn" target="_blank">
              {{ app.label || app.subdomain || app.fqdn }}
            </a>
          </template>
          <template #appTitle="app">
            {{ app.manifest.title }}
          </template>
          <template #fqdn="app">
            <a :href="'https://' + app.fqdn" target="_blank">
              {{ app.fqdn }}
            </a>
          </template>
          <template #status="app">
            <div class="list-status">
              {{ AppsModel.installationStateLabel(app) }}
              <ProgressBar v-if="app.progress && isOperator(app)" :busy="true" :value="Math.max(10, app.progress)" :show-label="false" class="apps-progress"/>
            </div>
          </template>
          <template #checklist="app">
            <a class="list-item-checklist-indicator" v-if="AppsModel.pendingChecklistItems(app)" :href="`#/app/${app.id}/info`"><Icon icon="fa-solid fa-triangle-exclamation"/></a>
          </template>
          <template #sso="app">
            <div v-show="app.type !== APP_TYPES.LINK">
              <Icon icon="fa-brands fa-openid" v-show="app.ssoAuth && app.manifest.addons.oidc" v-tooltip="$t('apps.auth.openid')" />
              <Icon icon="fas fa-user" v-show="app.ssoAuth && (!app.manifest.addons.oidc && !app.manifest.addons.email)" v-tooltip="$t('apps.auth.sso')" />
              <Icon icon="far fa-user" v-show="!app.ssoAuth && !app.manifest.addons.email" v-tooltip="$t('apps.auth.nosso')" />
              <Icon icon="fas fa-envelope" v-show="app.manifest.addons.email" v-tooltip="$t('apps.auth.email')" />
            </div>
          </template>
          <template #actions="app">
            <div style="text-align: right;">
              <Button tool plain secondary @click.capture="onActionMenu(app, $event)" icon="fa-solid fa-ellipsis" />
            </div>
          </template>
        </TableView>
      </div>

      <div class="empty-placeholder" v-if="apps.length === 0">
        <!-- admins or not-->
        <div v-if="profile.isAtLeastAdmin">
          <h4>{{ $t('apps.noApps.title') }}</h4>
          <h5 v-html="$t('apps.noApps.description', { appStoreLink: '#/appstore' })"></h5>
        </div>
        <div v-else>
          <h4>{{ $t('apps.noAccess.title') }}</h4>
          <h5>{{ $t('apps.noAccess.description') }}</h5>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

.grid-animation-move,
.grid-animation-enter-active,
.grid-animation-leave-active {
  transition: all 0.2s ease;
}

.grid-animation-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

.grid-animation-leave-to {
  opacity: 0;
  transform: translateY(-30px);
}

.list-icon {
  width: 32px;
  height: 32px;
}

.list-status {
  position: relative;
  height: 100%;
  display: flex;
  align-items: center;
}

.grid-item-task-label {
  opacity: 0.7;
  font-size: 12px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  color: var(--pankow-text-color);
}

.apps-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 4px;
}

.grid {
  display: flex;
  height: 100%;
  width: 100%;
  transition: 300ms;
  flex-wrap: wrap;
  justify-content: start;
  align-content: start;
}

.grid-item {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 190px;
  height: 180px;
  margin: 10px;
  overflow: hidden;
  border-radius: 10px;
  background-color: var(--card-background);
}

.grid-item:focus,
.grid-item:hover {
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
  background-color: var(--pankow-color-background-hover) !important;
  text-decoration: none;
}

.grid-item img {
  width: 80px;
  height: 80px;
  object-fit: cover;
}

.grid-item-label {
  font-size: 18px;
  font-weight: 100;
  margin: 5px 0 5px 0;
  color: var(--pankow-text-color);
  text-wrap: nowrap;
}

.config {
  position: absolute;
  color: var(--pankow-text-color);
  font-size: 18px;
  cursor: pointer;
  width: 50px;
  height: 50px;
  border-top-right-radius: 10px;
  right: 0;
  top: 0;
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.config:focus,
.config:hover {
  opacity: 1;
  color: var(--pankow-color-primary-hover);
}

@media (hover: none) {
  .config {
    opacity: 1;
  }
}

.grid-item:focus .config,
.grid-item:hover .config {
  opacity: 1;
}

.grid-item-indictors {
  position: absolute;
  left: 0;
  top: 0;
}

.grid-item-update-indicator {
  color: var(--pankow-color-success);
  font-size: 18px;
  width: 40px;
  height: 40px;
  border-top-right-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.grid-item-update-indicator:focus,
.grid-item-update-indicator:hover {
  opacity: 1;
  color: var(--pankow-color-success-hover);
}

.grid-item-checklist-indicator {
  color: var(--pankow-color-danger);
  border-radius: 50px;
  font-size: 18px;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.list-item-checklist-indicator {
  color: var(--pankow-color-danger);
}

.list-item-checklist-indicator:focus,
.list-item-checklist-indicator:hover,
.grid-item-checklist-indicator:focus,
.grid-item-checklist-indicator:hover {
  color: var(--pankow-color-danger-hover);
}

.empty-placeholder {
  font-size: 18px;
  margin: 10px;
}

</style>
