<script setup>

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

import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, ButtonGroup, ProgressBar, FormGroup, TextInput, Checkbox, TableView, Dialog } from 'pankow';
import { prettyLongDate } from 'pankow/utils';
import { TASK_TYPES, SECRET_PLACEHOLDER } from '../constants.js';
import Section from  '../components/Section.vue';
import BackupsModel from '../models/BackupsModel.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 props = defineProps({
  config: Object
});

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

const columns = {
  packageVersion: {
    label: t('backups.listing.version'),
    sort: true,
    hideMobile: true,
  },
  creationTime: {
    label: t('main.table.date'),
    sort: true
  },
  preserveSecs: {}, // archived
  content: {
    label: t('backups.listing.contents'),
    sort: false,
    hideMobile: true,
  },
  actions: {}
};

const busy = ref(true);
const backups = ref([]);
const taskLogsMenu = ref([]);
const lastTask = ref({});

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

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

  lastTask.value = result;

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

  setTimeout(waitForTask, 2000);
}

async function refreshTasks() {
  const [error, result] = await tasksModel.getByType(TASK_TYPES.TASK_BACKUP);
  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?taskId=${t.id}`); }
    };
  });

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

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

  // add contents property
  const appsById = {};
  const appsByFqdn = {};

  const [appsError, apps] = await appsModel.list();
  if (appsError) console.error(error);

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

  result.forEach(function (backup) {
    backup.contents = []; // { id, label, fqdn }
    backup.dependsOn.forEach(function (appBackupId) {
      const match = appBackupId.match(/app_(.*?)_.*/); // *? means non-greedy
      if (!match) return; // for example, 'mail'
      const app = appsById[match[1]];
      if (app) {
        backup.contents.push({
          id: app.id,
          label: app.label,
          fqdn: app.fqdn
        });
      } else {
        backup.contents.push({
          id: match[1],
          label: null,
          fqdn: null
        });
      }
    });
  });

  backups.value = result;
}

const startBackupError = ref('');
const startBackupBusy = ref(false);

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

  const [error] = await backupsModel.create();
  if (error) {
    if (error.status === 409) {
      if (error.body.message.indexOf('full_backup') !== -1) startBackupError.value = 'Backup already in progress. Please retry later.';
      else startBackupError.value = 'App task is currently in progress. Please retry later.';
    }

    return console.error(error);
  }

  await refreshTasks();

  startBackupBusy.value = false;
}

const stopBackupBusy = ref(false);

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

  const [error] = await tasksModel.stop(lastTask.value.id);
  if (error) return console.error(error);

  await refreshTasks();

  stopBackupBusy.value = false;
}

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

  // secrets and tokens already come with placeholder characters we remove them
  const tmp = {
    remotePath: backup.remotePath,
    encrypted: !!props.config.password  // we add this just to help the import UI
  };

  Object.keys(props.config).forEach((k) => {
    if (props.config[k] !== SECRET_PLACEHOLDER) tmp[k] = props.config[k];
  });

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


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


// 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.edit(editBackupId.value, editBackupLabel.value, editBackupPersist.value ? -1 : 0);
  if (error) {
    return console.error(error);
  }

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


onMounted(async () => {
  await refreshBackups();
  await refreshTasks();
  busy.value = false;
});

</script>

<template>
  <Section :title="$t('backups.listing.title')">
    <Dialog ref="infoDialog"
      :title="$t('backups.backupDetails.title')"
      :reject-label="$t('main.dialog.cancel')"
    >
      <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">{{ infoBackup.remotePath }}</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>
      <div class="info-row">
        <div class="info-label">{{ $t('backups.backupDetails.format') }}</div>
        <div class="info-value">{{ infoBackup.format }}</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>
      </div>
    </Dialog>

    <Dialog ref="editDialog"
      :title="$t('backups.backupEdit.title')"
      :reject-label="editBackupBusy ? '' : $t('main.dialog.cancel')"
       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 icon="fas fa-align-left" v-tooltip="$t('settings.updates.showLogsAction')" :menu="taskLogsMenu" :disabled="!taskLogsMenu.length"/>
    </template>

    <TableView :columns="columns" :model="backups" :busy="busy" @row-click="onInfo">
      <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 #actions="backup">
        <div class="table-actions">
          <ButtonGroup>
            <Button tool secondary small icon="fa-solid fa-circle-info" @click.stop="onInfo(backup)"></Button>
            <Button tool secondary small icon="fa-solid fa-pencil-alt" v-tooltip="$t('backups.listing.tooltipEditBackup')" @click.stop="onEdit(backup)"></Button>
            <Button tool secondary small icon="fa-solid fa-file-alt" v-tooltip="$t('backups.listing.tooltipDownloadBackupConfig')" @click.stop="onDownloadConfig(backup)"></Button>
          </ButtonGroup>
        </div>
      </template>
    </TableView>

    <br/>

    <div v-if="lastTask.active">
      <ProgressBar :value="lastTask.percent" />
      <div>{{ lastTask.message }}</div>
      <br/>
    </div>

    <div class="button-bar">
      <Button danger @click="onStopBackup()" v-if="lastTask.active" :loading="stopBackupBusy" :disabled="stopBackupBusy">{{ $t('backups.listing.stopTask') }}</Button>
      <Button @click="onStartBackup()" v-else :loading="startBackupBusy" :disabled="startBackupBusy">{{ $t('backups.listing.backupNow') }}</Button>

      <div class="error-label" v-if="startBackupError">{{ startBackupError }}</div>
    </div>
  </Section>
</template>
