<script setup>

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

import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, ClipboardAction, Menu, FormGroup, TextInput, Checkbox, TableView, Dialog } from '@cloudron/pankow';
import { prettyLongDate, prettyFileSize } from '@cloudron/pankow/utils';
import { TASK_TYPES } from '../constants.js';
import Section from  '../components/Section.vue';
import BackupsModel from '../models/BackupsModel.js';
import BackupSitesModel from '../models/BackupSitesModel.js';
import AppsModel from '../models/AppsModel.js';
import TasksModel from '../models/TasksModel.js';
import DashboardModel from '../models/DashboardModel.js';
import { download } from '../utils.js';

const backupsModel = BackupsModel.create();
const backupSitesModel = BackupSitesModel.create();
const appsModel = AppsModel.create();
const tasksModel = TasksModel.create();
const dashboardModel = DashboardModel.create();

const columns = {
  preserveSecs: {
    label: '',
    icon: 'fa-solid fa-archive',
    width: '40px',
    sort: true
  },
  packageVersion: {
    label: t('backups.listing.version'),
    sort: true,
    hideMobile: true,
  },
  site: {
    label: t('backup.target.label'),
    sort(a, b) {
      return b.name <= a.name ? 1 : -1;
    },
  },
  content: {
    label: t('backups.listing.contents'),
    sort: false,
    hideMobile: true,
  },
  size: {
    label: t('backup.target.size'),
    sort: true,
  },
  creationTime: {
    label: t('main.table.date'),
    sort: true
  },
  actions: {}
};

const actionMenuModel = ref([]);
const actionMenuElement = useTemplateRef('actionMenuElement');
function onActionMenu(backup, event) {
  actionMenuModel.value = [{
    icon: 'fa-solid fa-circle-info',
    label: t('backups.archives.info'),
    action: onInfo.bind(null, backup),
  }, {
    icon: 'fa-solid fa-pencil-alt',
    label: t('main.action.edit'),
    action: onEdit.bind(null, backup),
  }, {
    icon: 'fa-solid fa-file-alt',
    label: t('backups.listing.tooltipDownloadBackupConfig'),
    action: onDownloadConfig.bind(null, backup),
  }];

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

const busy = ref(true);
const backups = ref([]);
const taskLogsMenu = ref([]);
const trackingBackupTask = ref({});
const trackingCleanupTask = ref({});
const sites = ref([]);

async function waitForBackupTask(id) {
  if (!id || (trackingBackupTask.value.id && trackingBackupTask.value.id !== id)) return;

  const [error, result] = await tasksModel.get(id);
  if (error) return console.error(error);

  trackingBackupTask.value = result;

  // task done, refresh menu
  if (!result.active) {
    trackingBackupTask.value = {};
    refreshBackups();
    refreshTasks();
    return;
  }

  setTimeout(waitForBackupTask.bind(null, id), 2000);
}

async function waitForCleanupTask(id) {
  if (!id || (trackingCleanupTask.value.id && trackingCleanupTask.value.id !== id)) return;

  const [error, result] = await tasksModel.get(id);
  if (error) return console.error(error);

  trackingCleanupTask.value = result;

  // task done, refresh menu
  if (!result.active) {
    trackingCleanupTask.value = {};
    refreshBackups();
    refreshTasks();
    return;
  }

  setTimeout(waitForCleanupTask.bind(null, id), 2000);
}

async function refreshTasks() {
  let tasks = [];

  for (const site of sites.value) {
    const [error, results] = await tasksModel.getByType(TASK_TYPES.TASK_FULL_BACKUP_PREFIX + site.id);
    if (error) return console.error(error);

    results.forEach(r => r.siteName = site.name);
    tasks = tasks.concat(results);

    // if last task is currently active, start polling
    if (results[0] && results[0].active) waitForBackupTask(results[0].id);
  }

  for (const site of sites.value) {
    const [error, results] = await tasksModel.getByType(TASK_TYPES.TASK_CLEAN_BACKUPS_PREFIX + site.id);
    if (error) return console.error(error);

    results.forEach(r => r.siteName = site.name);
    tasks = tasks.concat(results);

    // if last task is currently active, start polling
    if (results[0] && results[0].active) waitForCleanupTask(results[0].id);
  }


  // limit to last 10
  tasks.sort((a, b) => b.creationTime < a.creationTime ? -1 : 1);
  taskLogsMenu.value = tasks.slice(0,10).map(t => {
    return {
      icon: 'fa-solid ' + ((!t.active && t.success) ? 'status-active fa-check-circle' : (t.active ? 'fa-circle-notch fa-spin' : 'status-error fa-times-circle')),
      label: `${prettyLongDate(t.ts)} - ${t.siteName} ${t.type.indexOf(TASK_TYPES.TASK_CLEAN_BACKUPS_PREFIX) === 0 ? 'cleanup' : 'backup'}`,
      action: () => { window.open(`/logs.html?taskId=${t.id}`); }
    };
  });
}

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

  result.forEach(function (backup) {
    backup.site = sites.value.find(t => t.id === backup.siteId);

    // filled when opening the info dialog - we only show apps for the moment
    backup.contents = backup.dependsOn.filter(c => c.indexOf('app_') === 0).map(c => {
      return {
        id: c,
        label: null,
        fqdn: null,
        stats: null
      };
    });
  });

  backups.value = result;
}

async function onDownloadConfig(backup) {
  const [error, dashboardConfig] = await dashboardModel.config();
  if (error) return console.error(error);

  const [backupConfigError, backupConfig] = await backupSitesModel.generateBackupConfig(backup);
  if (backupConfigError) return console.error(backupConfigError);

  const filename = `${dashboardConfig.adminFqdn}-backup-config-${(new Date(backup.creationTime)).toISOString().split('T')[0]}.json`;
  download(filename, JSON.stringify(backupConfig, null, 4));
}

// backups info dialog
const infoDialog = useTemplateRef('infoDialog');
const infoBackup = ref({ contents: [] });
async function onInfo(backup) {
  infoBackup.value = backup;
  infoDialog.value.open();

  // amend detailed app info
  const appsById = {};

  const [appsError, apps] = await appsModel.list();
  if (appsError) console.error('Failed to get apps list:', appsError);

  (apps || []).forEach(function (app) {
    appsById[app.id] = app;
  });

  for (const content of infoBackup.value.contents) {
    const match = content.id.match(/app_(.*?)_.*/); // *? means non-greedy
    if (!match) continue;
    const [error, backup] = await backupsModel.get(content.id);
    if (error) console.error(error);
    content.stats = backup.stats;
    const app = appsById[match[1]];
    if (app) {
      content.id = app.id;
      content.label = app.label;
      content.fqdn = app.fqdn;
    } else {
      content.id = match[1];
    }
  }
}

// edit backups dialog
const editDialog = useTemplateRef('editDialog');
const editBackupError = ref('');
const editBackupBusy = ref(false);
const editBackupId = ref('');
const editBackupLabel = ref('');
const editBackupPersist = ref(false);
function onEdit(backup) {
  editBackupError.value = '';
  editBackupBusy.value = false;
  editBackupId.value = backup.id;
  editBackupLabel.value = backup.label;
  editBackupPersist.value = backup.preserveSecs === -1;
  editDialog.value.open();
}

async function onEditSubmit() {
  editBackupBusy.value = true;

  const [error] = await backupsModel.update(editBackupId.value, editBackupLabel.value, editBackupPersist.value ? -1 : 0);
  if (error) {
    return console.error(error);
  }

  await refreshBackups();
  editBackupBusy.value = false;
  editDialog.value.close();
}

async function refresh() {
  await refreshBackups();
  await refreshTasks();
}

onMounted(async () => {
  const [error, result] = await backupSitesModel.list();
  if (error) return console.error(error);

  sites.value = result;

  await refreshBackups();

  busy.value = false;

  await refreshTasks();
});

defineExpose({ refresh });

</script>

<template>
  <Section :title="$t('backups.listing.title')">
    <Menu ref="actionMenuElement" :model="actionMenuModel" />

    <Dialog ref="infoDialog"
      :title="$t('backups.backupDetails.title')"
      :reject-label="$t('main.dialog.close')"
    >
      <div class="info-row">
        <div class="info-label">{{ $t('backups.backupDetails.id') }}</div>
        <div class="info-value">{{ infoBackup.id }}</div>
      </div>
      <div class="info-row">
        <div class="info-label">{{ $t('backups.backupEdit.label') }}</div>
        <div class="info-value">{{ infoBackup.label }}</div>
      </div>
      <div class="info-row">
        <div class="info-label">{{ $t('backups.backupEdit.remotePath') }}</div>
        <div class="info-value">
          <div>
            {{ infoBackup.remotePath }}
            <ClipboardAction plain :value="infoBackup.remotePath"/>
          </div>
        </div>
      </div>
      <div class="info-row">
        <div class="info-label">{{ $t('backups.backupDetails.date') }}</div>
        <div class="info-value">{{ prettyLongDate(infoBackup.creationTime) }}</div>
      </div>
      <div class="info-row">
        <div class="info-label">{{ $t('backups.backupDetails.version') }}</div>
        <div class="info-value">{{ infoBackup.packageVersion }}</div>
      </div>

      <br/>

      <p class="text-muted">{{ $t('backups.backupDetails.list', { appCount: infoBackup.contents.length }) }}:</p>
      <div v-for="content in infoBackup.contents" :key="content.id">
        <a v-if="content.fqdn" :href="`/#/app/${content.id}/backups`">{{ content.label || content.fqdn }}</a>
        <a v-else :href="`/#/system-eventlog?search=${content.id}`">{{ content.id }}</a>
        <span v-if="content.stats">&nbsp;{{ prettyFileSize(content.stats.size) }} - {{ content.stats.fileCount }} file(s)</span>
      </div>
    </Dialog>

    <Dialog ref="editDialog"
      :title="$t('backups.backupEdit.title')"
      :reject-label="$t('main.dialog.cancel')"
      :reject-active="!editBackupBusy"
       reject-style="secondary"
      :confirm-label="$t('main.dialog.save')"
      :confirm-busy="editBackupBusy"
      @confirm="onEditSubmit()"
    >
      <p class="has-error text-center" v-show="editBackupError">{{ editBackupError }}</p>

      <form @submit.prevent="onEditSubmit()" autocomplete="off">
        <fieldset>
          <FormGroup>
            <label for="backupLabelInput">{{ $t('backups.backupEdit.label') }}</label>
            <TextInput id="backupLabelInput" v-model="editBackupLabel" />
          </FormGroup>

          <Checkbox v-model="editBackupPersist" :label="$t('backups.backupEdit.preserved.description')" />
          <!-- <sup><a popover-placement="top-right" popover-trigger="outsideClick" uib-popover="{{ 'backups.backupEdit.preserved.tooltip' | tr: { appsLength: editBackup.backup.contents.length} }}"><i class="fa fa-question-circle"></i></a></sup> -->
        </fieldset>
      </form>
    </Dialog>

    <template #header-buttons>
      <Button tool secondary :menu="taskLogsMenu" :disabled="!taskLogsMenu.length">{{ $t('main.action.logs') }}</Button>
    </template>

    <TableView :columns="columns" :model="backups" :busy="busy" :placeholder="$t('backups.listing.noBackups')">
      <template #preserveSecs="backup">
        <i class="fas fa-archive" v-show="backup.preserveSecs === -1" v-tooltip="$t('backups.listing.tooltipPreservedBackup')"></i>
      </template>

      <template #creationTime="backup">{{ prettyLongDate(backup.creationTime) }} <b v-show="backup.label">({{ backup.label }})</b></template>

      <template #content="backup">
        <span v-if="backup.contents.length">{{ $t('backups.listing.appCount', { appCount: backup.contents.length }) }}</span>
        <span v-else>{{ $t('backups.listing.noApps') }}</span>
      </template>

      <template #size="backup">
        <span v-if="backup.stats?.aggregated">{{ prettyFileSize(backup.stats.aggregated.size) }} - {{ backup.stats.aggregated.fileCount }} file(s)</span>
      </template>

      <template #site="backup">{{ backup.site.name }}</template>

      <template #actions="backup">
        <div style="text-align: right;">
          <Button tool plain secondary @click.capture="onActionMenu(backup, $event)" icon="fa-solid fa-ellipsis" />
        </div>
      </template>
    </TableView>
  </Section>
</template>
