<script setup>

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

import { ref, onMounted, onUnmounted, useTemplateRef } from 'vue';
import { Button, Switch, Checkbox, FormGroup, TextInput, TableView, Dialog, ProgressBar, Spinner } from '@cloudron/pankow';
import { prettyLongDate, prettyFileSize } from '@cloudron/pankow/utils';
import { API_ORIGIN, RSTATES } from '../../constants.js';
import { download } from '../../utils.js';
import AppImportDialog from '../AppImportDialog.vue';
import AppRestoreDialog from '../AppRestoreDialog.vue';
import SettingsItem from '../SettingsItem.vue';
import AppsModel from '../../models/AppsModel.js';
import BackupSitesModel from '../../models/BackupSitesModel.js';
import BackupsModel from '../../models/BackupsModel.js';
import BackupInfoDialog from '../BackupInfoDialog.vue';
import ActionBar from '../../components/ActionBar.vue';

const appsModel = AppsModel.create();
const backupSitesModel = BackupSitesModel.create();
const backupsModel = BackupsModel.create();

const props = defineProps([ 'app' ]);

const columns = ref({
  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;
    },
  },
  size: {
    label: t('backup.target.size'),
    sort: true,
    hideMobile: true,
  },
  packageVersion: {
    label: t('main.table.version'),
    sort: true,
  },
  integrity: {
    label: 'Integrity',
    sort: false,
    width: '100px',
    align: 'center',
  },
  actions: {
    label: '',
    sort: false,
    width: '100px',
  }
});

const accessLevel = props.app.accessLevel;

function createActionMenu(backup) {
  return [{
    icon: 'fa-solid fa-info',
    label: t('backups.archives.info'),
    action: onInfo.bind(null, backup),
  }, {
    icon: 'fa-solid fa-pencil-alt',
    label: t('main.action.edit'),
    visible: accessLevel === 'admin',
    action: onEdit.bind(null, backup),
  }, {
    separator: true,
  }, {
    icon: 'fa-solid fa-download',
    label: t('app.backups.backups.downloadBackupTooltip'),
    visible: backup.site.format === 'tgz' && accessLevel === 'admin',
    href: getDownloadLink(backup),
  }, {
    icon: 'fa-solid fa-file-alt',
    label: t('app.backups.backups.downloadConfigTooltip'),
    visible: accessLevel === 'admin',
    action: onDownloadConfig.bind(null, backup),
  },  {
    separator: true,
    visible: accessLevel === 'admin',
  }, {
    icon: 'fa-solid fa-clone',
    label: t('app.backups.backups.cloneTooltip'),
    visible: accessLevel === 'admin',
    action: onClone.bind(null, backup),
  }, {
    icon: 'fa-solid fa-history',
    label: t('app.backups.backups.restoreTooltip'),
    disabled: !!props.app.taskId || props.app.runState === 'stopped',
    action: onRestore.bind(null, backup),
    quickAction: true
  },  {
    separator: true,
  }, {
    icon: 'fa-solid fa-key',
    label: backup.integrityCheckTask?.active ? t('backups.stopIntegrity') : t('backups.checkIntegrity'),
    visible: accessLevel === 'admin',
    action: backup.integrityCheckTask?.active ? onStopIntegrityCheck.bind(null, backup) : onStartIntegrityCheck.bind(null, backup),
  }];
}

const busy = ref(true);
const errorMessage = ref('');
const editBusy = ref(false);
const editError = ref('');
const editBackup = ref({});
const editPersist = ref(false);
const editLabel = ref('');
const importBusy = ref(false);
const autoBackupsEnabled = ref(false);
const backups = ref([]);
const infoDialog = useTemplateRef('infoDialog');
const editDialog = useTemplateRef('editDialog');
const restoreDialog = useTemplateRef('restoreDialog');
const taskLogsMenu = ref([]);
const lastTask = ref({});
const startBackupBusy = ref(false);
const stopBackupBusy = ref(false);
const backupSitesMenu = ref([]);
const backupSites = ref([]);

async function onChangeAutoBackups(value) {
  const [error] = await appsModel.configure(props.app.id, 'automatic_backup', { enable: value });
  if (error) {
    autoBackupsEnabled.value = !value;
    return console.error(error);
  }
}

async function waitForTask() {
  if (!lastTask.value.id) return;

  const [error, result] = await appsModel.getAppTask(props.app.id, lastTask.value.id);
  if (error) return console.error(error);

  lastTask.value = result;

  // task done, refresh menu
  if (!result.active) {
    startBackupBusy.value = false;
    await refreshTasks();
    refreshBackupList();
    return;
  }

  setTimeout(waitForTask, 2000);
}

async function refreshTasks() {
  const [error, result] = await appsModel.listTasks(props.app.id);
  if (error) return console.error(error);

  lastTask.value = result[0] || {};

  // limit to last 10
  taskLogsMenu.value = result.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),
      action: () => { window.open(`/logs.html?appId=${props.app.id}&taskId=${t.id}`); }
    };
  });

  // if last task is currently active, start polling
  if (lastTask.value.active) waitForTask();
}

async function onStartBackup(backupSiteId) {
  startBackupBusy.value = true;

  const [error] = await appsModel.backup(props.app.id, backupSiteId);
  if (error) return console.error(error);

  await refreshTasks();
}

async function onStopBackup() {
  stopBackupBusy.value = true;

  const [error] = await appsModel.stopAppTask(props.app.id, lastTask.value.id);
  if (error) return console.error(error);

  await refreshTasks();

  stopBackupBusy.value = false;
}

function onInfo(backup) {
  infoDialog.value.open(backup);
}

function onEdit(backup) {
  editBusy.value = false;
  editBackup.value = backup;
  editPersist.value = backup.preserveSecs === -1;
  editLabel.value = backup.label || '';
  editError.value = '';
  editDialog.value.open();
}

async function onEditSubmit() {
  const [error] = await appsModel.updateBackup(props.app.id, editBackup.value.id, editLabel.value, editPersist.value  ? -1 : 0);
  if (error) {
    editError.value = error.body ? error.body.message : 'Internal error';
    editBusy.value = false;
    return console.error(error);
  }

  refreshBackupList();
  editDialog.value.close();
}

function getDownloadLink(backup) {
  const accessToken = localStorage.token;
  return `${API_ORIGIN}/api/v1/apps/${props.app.id}/backups/${backup.id}/download?access_token=${accessToken}`;
}

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

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

const restoreBusy = ref(false);
const restoreBackup = ref({});

async function onRestore(backup) {
  restoreBusy.value = false;
  restoreBackup.value = backup;
  restoreDialog.value.open();
}

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

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

async function onRestoreSubmit() {
  restoreBusy.value = true;

  const [error] = await appsModel.restore(props.app.id, restoreBackup.value.id);
  if (error) {
    restoreBusy.value = false;
    return console.error(error);
  }

  restoreDialog.value.close();
}

const importDialog = useTemplateRef('importDialog');
function onImport() {
  importDialog.value.open(props.app.id);
}

const cloneDialog = useTemplateRef('cloneDialog');
function onClone(backup) {
  cloneDialog.value.open(backup, props.app.id);
}

const INTEGRITY_POLL_INTERVAL_MS = 5000;
let integrityPollTimer = null;

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

async function refreshBackupList() {
  const [error, result] = await appsModel.backups(props.app.id);
  if (error) return console.error(error);

  for (const backup of result) {
    backup.site = backupSites.value.find(t => t.id === backup.siteId);
  }
  backups.value = result;

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

onMounted(async () => {
  autoBackupsEnabled.value = props.app.enableBackup;

  const [error, result] = await appsModel.listBackupSites(props.app.id);
  if (error) return console.error(error);

  backupSites.value = result;
  backupSitesMenu.value = result.map(site => {
    return {
      label: site.name,
      action: onStartBackup.bind(null, site.id),
    };
  });

  await refreshBackupList();
  await refreshTasks();

  busy.value = false;
});

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

</script>

<template>
  <div>
    <AppRestoreDialog ref="cloneDialog"/>
    <AppImportDialog ref="importDialog"/>

    <BackupInfoDialog ref="infoDialog" />

    <Dialog ref="editDialog"
      :title="$t('backups.backupEdit.title')"
      :reject-label="$t('main.dialog.cancel')"
       reject-style="secondary"
      :confirm-label="$t('main.dialog.save')"
      :confirm-active="true"
      :confirm-busy="editBusy"
      @confirm="onEditSubmit()"
    >
      <div>
        <form @submit.prevent="onEditSubmit()" autocomplete="off">
          <fieldset :disabled="editBusy">
            <div class="has-error" v-show="editError">{{ editError }}</div>

            <FormGroup>
              <label for="labelInput">{{ $t('backups.backupEdit.label') }}</label>
              <TextInput v-model="editLabel" id="labelInput" />
            </FormGroup>

            <Checkbox v-model="editPersist" :label="$t('backups.backupEdit.preserved.description')" help-url="https://docs.cloudron.io/backups#backup-labels"/>
          </fieldset>
        </form>
      </div>
    </Dialog>

    <Dialog ref="restoreDialog"
      :title="$t('app.restoreDialog.title')"
      :reject-label="$t('main.dialog.cancel')"
       reject-style="secondary"
      :confirm-label="$t('app.restoreDialog.restoreAction')"
      :confirm-active="true"
      :confirm-busy="restoreBusy"
      @confirm="onRestoreSubmit()"
    >
      <div>
        <p class="text-danger">{{ $t('app.restoreDialog.warning') }}</p>
        <p>{{ $t('app.restoreDialog.description', { fqdn: app.fqdn, creationTime: prettyLongDate(restoreBackup.creationTime) }) }}</p>
      </div>
    </Dialog>

    <SettingsItem>
      <FormGroup>
        <label>{{ $t('app.backups.auto.title') }}</label>
        <div v-html="$t('app.backups.auto.description')"></div>
      </FormGroup>
      <Switch v-model="autoBackupsEnabled" @change="onChangeAutoBackups"/>
    </SettingsItem>

    <hr style="margin-top: 20px"/>

    <div>
      <label>{{ $t('app.backups.import.title') }}</label>
      <div>{{ $t('app.backups.import.description') }}</div>
    </div>
    <br/>
    <Button @click="onImport()" :loading="importBusy" :disabled="importBusy || !!app.taskId || app.runState === 'stopped'" v-tooltip="app.taskId ? 'App is not running' : ''">{{ $t('app.backups.backups.importAction') }}</Button>

    <hr style="margin-top: 20px"/>

    <SettingsItem>
      <FormGroup>
        <label>{{ $t('app.backups.backups.title') }}</label>
        <div>{{ $t('app.backups.backups.description') }}</div>
      </FormGroup>
      <div style="display: flex; align-items: center;">
        <Button tool secondary :menu="taskLogsMenu" :disabled="!taskLogsMenu.length">{{ $t('main.action.logs') }}</Button>
      </div>
    </SettingsItem>

    <div class="error-label" v-if="errorMessage">{{ errorMessage }}</div>

    <div v-if="lastTask.active">
      <div style="margin-top: 10px; display: flex; align-items: center; gap: 10px; overflow: hidden;">
        <div style="flex-grow: 1; overflow: hidden;">
          <ProgressBar :value="lastTask.percent" :show-label="false" :busy="true" :mode="lastTask.percent <= 0 ? 'indeterminate' : ''"/>
          <a :href="`/logs.html?appId=${props.app.id}&taskId=${lastTask.id}`" target="_blank" style="display: block; margin-top: 3px; max-width: 100%; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;">{{ lastTask.percent }}% {{ lastTask.message }}</a>
        </div>
        <Button danger plain tool icon="fa-solid fa-xmark" @click="onStopBackup()" :loading="stopBackupBusy" :disabled="stopBackupBusy"></Button>
      </div>
    </div>
    <div v-else>
      <Button v-if="backupSites.length <= 1" @click="onStartBackup(backupSites[0].id)" :loading="startBackupBusy" :disabled="!backupSites.length || app.runState === RSTATES.STOPPED || startBackupBusy || !!app.error">{{ $t('app.backups.backups.createBackupAction') }}</Button>
      <Button v-else :menu="backupSitesMenu" :loading="startBackupBusy" :disabled="app.runState === RSTATES.STOPPED || startBackupBusy || !!app.error">{{ $t('app.backups.backups.createBackupAction') }}</Button>
    </div>

    <br/>

    <TableView :model="backups" :columns="columns" :busy="busy" :placeholder="$t('backups.listing.noBackups')" style="max-height: 400px;" >
      <template #creationTime="{ item }">
        <div>
          <span>{{ prettyLongDate(item.creationTime) }}</span>
          <span v-if="item.label">&nbsp;<b>{{ item.label }}</b></span>
          <span>&nbsp;<i class="fa-solid fa-thumbtack text-muted" v-show="item.preserveSecs === -1" v-tooltip="$t('backups.listing.tooltipPreservedBackup')"></i></span>
        </div>
      </template>
      <template #site="{ item }">
        {{ item.site.name }}
      </template>
      <template #size="{ item }">
        <span v-if="item.stats?.upload">{{ prettyFileSize(item.stats.upload.size) }} - {{ item.stats.upload.fileCount }} file(s)</span>
      </template>
      <template #integrity="{ item }">
        <Spinner v-if="item.integrityCheckTask?.active" style="min-width: 0;"/>
        <div v-else-if="item.lastIntegrityCheckTime" style="display: flex; align-items: center; justify-content: center;">
          <i class="fa-solid" :class="{ 'fa-check-circle text-success': item.integrityCheckStatus === 'passed', 'fa-times-circle text-danger': item.integrityCheckStatus === 'failed', 'fa-circle-minus text-warning': item.integrityCheckStatus === 'skipped' }" v-tooltip="prettyLongDate(item.lastIntegrityCheckTime)"></i>
        </div>
        <div v-else style="text-align: center;">-</div>
      </template>
      <template #actions="{ item }">
        <ActionBar :actions="createActionMenu(item)"/>
      </template>
    </TableView>
  </div>
</template>
