<template>
  <div>
    <ApplinkDialog ref="applinkDialog" @success="refreshApps()"/>

    <h1 class="section-header">
      {{ $t('apps.title') }}
      <div>
        <TextInput v-model="filter" placeholder="Filter ..." />
        <ButtonGroup>
          <Dropdown outline tool :options="tagFilterOptions" option-key="id" option-label="name" v-model="tagFilter"></Dropdown>
          <Dropdown outline tool :options="stateFilterOptions" option-key="id" v-model="stateFilter"></Dropdown>
          <Dropdown outline tool :options="domainFilterOptions" option-key="id" option-label="domain" v-model="domainFilter"></Dropdown>
        </ButtonGroup>
        <Button tool @click="toggleView()" :icon="viewType === VIEW_TYPE.GRID ? 'fas fa-list' : 'fas fa-grip'"></Button>
      </div>
    </h1>

    <div v-show="ready">
      <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" v-tooltip="app.fqdn">
          <div class="config" v-show="isOperator(app)" @click.prevent="openAppEdit(app)"><Icon icon="fa-solid fa-cog" /></div>
          <img :src="API_ORIGIN + app.iconUrl" v-fallback-image="API_ORIGIN + '/img/appicon_fallback.png'"/>
          <div class="grid-item-label">{{ app.label || app.subdomain || app.fqdn }}</div>
          <div class="grid-item-task-label">{{ installationStateLabel(app) }}</div>
          <div class="apps-progress" v-show="isOperator(app)">
            <div class="apps-progress-filled" :style="{ width: app.progress+'%' }"></div>
          </div>
        </a>
      </TransitionGroup>

      <div class="list" v-if="viewType === VIEW_TYPE.LIST">
        <TableView :columns="listColumns" :model="filteredApps">
          <template #icon="slotProps">
            <a :href="'https://' + slotProps.fqdn" target="_blank">
              <img class="list-icon" :src="API_ORIGIN + slotProps.iconUrl" v-fallback-image="API_ORIGIN + '/img/appicon_fallback.png'"/>
            </a>
          </template>
          <template #label="slotProps">
            <a :href="'https://' + slotProps.fqdn" target="_blank" v-tooltip="slotProps.fqdn">
              {{ slotProps.label || slotProps.subdomain || slotProps.fqdn }}
            </a>
          </template>
          <template #appTitle="slotProps">
            {{ slotProps.manifest.title }}
          </template>
          <template #domain="slotProps">
            <a :href="'https://' + slotProps.fqdn" target="_blank">
              {{ slotProps.fqdn }}
            </a>
          </template>
          <template #status="slotProps">
            <div class="list-status">
              {{ installationStateLabel(slotProps) }}
              <div class="apps-progress" v-show="isOperator(slotProps)">
                <div class="apps-progress-filled" :style="{ width: slotProps.progress+'%' }"></div>
              </div>
            </div>
          </template>
          <template #sso="slotProps">
            <div v-show="slotProps.type !== APP_TYPES.LINK">
              <Icon icon="fa-brands fa-openid" v-show="slotProps.ssoAuth && slotProps.manifest.addons.oidc" v-tooltip="$t('apps.auth.openid')" />
              <Icon icon="fas fa-user" v-show="slotProps.ssoAuth && (!slotProps.manifest.addons.oidc && !slotProps.manifest.addons.email)" v-tooltip="$t('apps.auth.sso')" />
              <Icon icon="far fa-user" v-show="!slotProps.ssoAuth && !slotProps.manifest.addons.email" v-tooltip="$t('apps.auth.nosso')" />
              <Icon icon="fas fa-envelope" v-show="slotProps.manifest.addons.email" v-tooltip="$t('apps.auth.email')" />
            </div>
          </template>
          <template #actions="slotProps">
            <div class="actions">
              <ButtonGroup>
                <Button tool v-if="slotProps.type !== APP_TYPES.LINK" :href="'/logs.html?appId=' + slotProps.id" target="_blank" v-tooltip="$t('app.logsActionTooltip')" icon="fas fa-align-left"></Button>
                <Button tool v-if="slotProps.type !== APP_TYPES.PROXIED && slotProps.type !== APP_TYPES.LINK" :href="'/terminal.html?id=' + slotProps.id" target="_blank" v-tooltip="$t('app.terminalActionTooltip')" icon="fa fa-terminal"></Button>
                <Button tool v-if="slotProps.manifest.addons.localstorage" :href="'/filemanager.html#/home/app/' + slotProps.id" target="_blank" v-tooltip="$t('app.filemanagerActionTooltip')" icon="fas fa-folder"></Button>
              </ButtonGroup>

              <Button tool @click="openAppEdit(slotProps)" icon="fa-solid fa-cog"></Button>
            </div>
          </template>
        </TableView>
      </div>

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

        <!-- for non-admins -->
        <div v-if="!profile.isAtLeastAdmin">
          <h4>{{ $t('apps.noAccess.title') }}</h4>
          <h5>{{ $t('apps.noAccess.description') }}</h5>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { Button, ButtonGroup, Dropdown, Icon, TableView, TextInput } from 'pankow';

import { 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 './ApplinkDialog.vue';

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

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

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

let refreshInterval;

export default {
  name: 'AppsView',
  components: {
    ApplinkDialog,
    Button,
    ButtonGroup,
    Dropdown,
    Icon,
    TableView,
    TextInput,
  },
  data() {
    return {
      API_ORIGIN,
      APP_TYPES,
      VIEW_TYPE,
      ready: false,
      filter: '',
      profile: this.$root.profile,
      apps: [],
      viewType: (localStorage.appsView && (localStorage.appsView === VIEW_TYPE.GRID || localStorage.appsView === VIEW_TYPE.LIST)) ? localStorage.appsView : VIEW_TYPE.GRID,
      tagFilter: '',
      tagFilterOptions: [{
        id: '',
        name: 'All Tags',
      }],
      domainFilter: '',
      domainFilterOptions: [{
        id: '',
        domain: 'All Domains',
      }],
      stateFilter: '',
      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' },
      ],
      listColumns: {
        icon: {
          width: '32px'
        },
        label: {
          label: 'Label',
          sort: true
        },
        domain: {
          label: 'Location',
          sort: true
        },
        status: {},
        appTitle: {
          label: 'App Title',
          sort: true
        },
        sso: {
          label: 'Login',
          sort: true
        },
        actions: {}
      },
    };
  },
  computed: {
    filteredApps() {
      return this.apps.filter(a => {
        return a.fqdn.indexOf(this.filter) !== -1;
      }).filter(a => {
        if (!this.domainFilter) return true;
        return a.domain === this.domainFilter;
      }).filter(a => {
        if (!this.tagFilter) return true;
        return a.tags.indexOf(this.tagFilter) !== -1;
      }).filter(a => {
        if (!this.stateFilter) return true;

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

        // TODO implement this
        // if (this.stateFilter === 'update_available') return !!(Client.getConfig().update[a.id] && Client.getConfig().update[a.id].manifest.version && Client.getConfig().update[a.id].manifest.version !== a.manifest.version);
        if (this.stateFilter === 'update_available') return false;

        return a.runState === RSTATES.RUNNING && (a.health !== HSTATES.HEALTHY || a.installationState !== ISTATES.INSTALLED); // not responding
      });
    },
  },
  methods: {
    installationStateLabel: AppsModel.installationStateLabel,
    installationActive: AppsModel.installationActive,
    appProgressMessage: AppsModel.appProgressMessage,
    openAppEdit(app) {
      if (app.type === APP_TYPES.LINK) this.$refs.applinkDialog.open(app);
      else window.location.href = `#/app/${app.id}/info`;
    },
    onOpenApp(app, event) {
      function stopEvent() {
        event.stopPropagation();
        event.preventDefault();
      }

      if (app.installationState !== ISTATES.INSTALLED) {
        if (app.installationState === ISTATES.ERROR && this.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 (this.isOperator(app)) window.location.href = `#/app/${app.id}/repair`;
        return stopEvent();
      }

      // TODO
      // if (app.pendingPostInstallConfirmation && $scope.appPostInstallConfirm) {
      //     $scope.appPostInstallConfirm.show(app);
      //     return stopEvent();
      // }
    },
    isOperator(app) {
      return app.accessLevel === 'operator' || app.accessLevel === 'admin';
    },
    async refreshApps() {
      const apps = await appsModel.list();
      const applinks = await applinksModel.list();

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

        apps.push(applink);
      }

      this.apps = apps;

      // gets all tags used by all apps, flattens the arrays and new Set() will dedupe
      const tags = [...new Set(this.apps.map(a => a.tags).flat())].map(t => { return { id: t, name: t }; });
      this.tagFilterOptions = [{ id: '', name: 'All Tags', }].concat(tags);
    },
    toggleView() {
      this.viewType = this.viewType === VIEW_TYPE.LIST ? VIEW_TYPE.GRID : VIEW_TYPE.LIST;
      localStorage.appsView = this.viewType;
    },
  },
  async mounted() {
    await this.refreshApps();

    const domains = await domainsModel.list();
    this.domainFilterOptions = this.domainFilterOptions.concat(domains.map(d => { d.id = d.domain; return d; }));
    this.domainFilter = this.domainFilterOptions[0].id;

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

    this.ready = true;

    refreshInterval = setInterval(this.refreshApps, 5000);
  },
  async unmounted() {
    clearInterval(refreshInterval);
  }
};

</script>

<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: 5px;
  text-align: center;
  border-radius: 10px;
  color: var(--pankow-text-color);
}

.apps-progress-filled {
  background-color: var(--pankow-color-primary);
  position: absolute;
  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: apps-progress-bar-stripes 1s linear infinite;
  transition: width 300ms;
}

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

.actions {
  text-align: right;
  visibility: hidden;
}

tr:hover .actions {
  visibility: visible;
}

.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);
  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);
}

.grid-item:focus .grid-item-label,
.grid-item:hover .grid-item-label {
  text-decoration: none;
  color: var(--accent-color);;
}

.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 {
  text-decoration: none;
  color: var(--accent-color);;
  opacity: 1;
}

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

.empty-placeholder {
  margin-top: 20px;
}

</style>
