<script setup>

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

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

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

const columns = {
  creationTime: {
    label: t('main.table.created'),
    sort(a, b) {
      return new Date(a) - new Date(b);
    }
  },
  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: false,
    hideMobile: true,
  },
  packageVersion: {
    label: t('backups.listing.version'),
    sort: true,
    hideMobile: true,
  },
  integrity: {
    label: 'Integrity',
    sort: false,
    width: '100px',
    align: 'center',
  },
  actions: {}
};

function createActionMenu(backup) {
  return [{
    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),
  }, {
    separator: true,
  }, {
    icon: 'fa-solid fa-key',
    label: backup.integrityCheckTask?.active ? t('backups.stopIntegrity') : t('backups.checkIntegrity'),
    action: backup.integrityCheckTask?.active ? onStopIntegrityCheck.bind(null, backup) : onStartIntegrityCheck.bind(null, backup),
  }];
}

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

const INTEGRITY_POLL_INTERVAL_MS = 5000;
let integrityPollTimer = null;

function scheduleIntegrityPoll() {
  if (integrityPollTimer) return;
  integrityPollTimer = setTimeout(async () => {
    integrityPollTimer = null;
    await refreshBackups();
    if (backups.value.some(b => b.integrityCheckTask?.active)) scheduleIntegrityPoll();
  }, INTEGRITY_POLL_INTERVAL_MS);
}

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);
    backup.appCount = backup.dependsOn.filter(c => c.indexOf('app_') === 0).length;
  });

  backups.value = result;

  if (result.some(b => b.integrityCheckTask?.active)) scheduleIntegrityPoll();
}

async function onStartIntegrityCheck(backup) {
  const [error] = await backupsModel.startIntegrityCheck(backup.id);
  if (error) return window.cloudron.onError(error);
  await refreshBackups();
}

async function onStopIntegrityCheck(backup) {
  const [error] = await backupsModel.stopIntegrityCheck(backup.id);
  if (error) return window.cloudron.onError(error);
  await refreshBackups();
}

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

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

const infoDialog = useTemplateRef('infoDialog');
async function onInfo(backup) {
  infoDialog.value.open(backup);
}

// 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) {
    editBackupBusy.value = false;
    editBackupError.value = error.body?.message || JSON.stringify(error);
    return;
  }

  await refreshBackups();
  editDialog.value.close();
}

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

onMounted(async () => {
  await refreshBackupSites();
  await refreshBackups();

  busy.value = false;

  await refreshTasks();
});

onUnmounted(() => {
  if (integrityPollTimer) clearTimeout(integrityPollTimer);
});

defineExpose({ refresh });

</script>

<template>
  <Section :title="$t('backups.listing.title')">
    <BackupInfoDialog ref="infoDialog" />

    <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()"
    >
      <div class="has-error text-center" v-show="editBackupError">{{ editBackupError }}</div>

      <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')" help-url="https://docs.cloudron.io/backups#backup-labels"/>
          <!-- <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>

    <div v-html="t('backups.listing.description', { restoreLink: 'https://docs.cloudron.io/backups/#restore-cloudron', migrateLink: 'https://docs.cloudron.io/backups/#move-cloudron-to-another-server' })"></div>

    <br/>

    <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 #creationTime="{ item:backup }">
        <div>
          <span>{{ prettyLongDate(backup.creationTime) }}</span>
          <span v-if="backup.label">&nbsp;<b>{{ backup.label }}</b></span>
          <span>&nbsp;<i class="fa-solid fa-thumbtack text-muted" v-show="backup.preserveSecs === -1" v-tooltip="$t('backups.listing.tooltipPreservedBackup')"></i></span>
        </div>
      </template>

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

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

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

      <template #integrity="{ item:backup }">
        <Spinner v-if="backup.integrityCheckTask?.active" style="min-width: 0;"/>
        <div v-else-if="backup.lastIntegrityCheckTime" style="display: flex; align-items: center; justify-content: center;">
          <i class="fa-solid" :class="{ 'fa-check-circle text-success': backup.integrityCheckStatus === 'passed', 'fa-times-circle text-danger': backup.integrityCheckStatus === 'failed', 'fa-circle-minus text-warning': backup.integrityCheckStatus === 'skipped' }" v-tooltip="prettyLongDate(backup.lastIntegrityCheckTime)"></i>
        </div>
        <div v-else style="text-align: center;">-</div>
      </template>

      <template #actions="{ item:backup }">
        <ActionBar :actions="createActionMenu(backup)"/>
      </template>
    </TableView>
  </Section>
</template>
