<script setup>

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

import { ref, onMounted, useTemplateRef } from 'vue';
import { Icon, Button, Switch, Checkbox, FormGroup, TextInput, TableView, ButtonGroup, Dialog } from 'pankow';
import { prettyLongDate } from 'pankow/utils';
import { API_ORIGIN, SECRET_PLACEHOLDER } 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 BackupsModel from '../../models/BackupsModel.js';
import TasksModel from '../../models/TasksModel.js';

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

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

const columns = ref({
  preserveSecs: {
    label: '',
    icon: 'fa-solid fa-archive',
    width: '40px',
    sort: true
  },
  packageVersion: {
    label: t('app.backups.backups.packageVersion'),
    sort: true,
  },
  creationTime: {
    label: t('app.backups.backups.time'),
    sort: true,
  },
  actions: {
    label: '',
    sort: false,
  }
});

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 createBusy = ref(false);
const importBusy = ref(false);
const autoBackupsEnabled = ref(false);
const backups = ref([]);
const editDialog = useTemplateRef('editDialog');
const restoreDialog = useTemplateRef('restoreDialog');

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(taskId) {
  if (!taskId) return;

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

  if (!result.active) return refresh();

  setTimeout(waitForTask.bind(null, taskId), 2000);
}

async function onCreate() {
  createBusy.value = true;
  const [error, result] = await appsModel.backup(props.app.id);
  if (error) return console.error(error);

  setTimeout(() => createBusy.value = false, 2000);

  await waitForTask(result);
}

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

  refresh();
  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 [error, backupConfig] = await backupsModel.getConfig();
  if (error) return console.error(error);

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

  Object.keys(backupConfig).forEach(k => {
    const v = backupConfig[k];
    if (v && typeof v === 'object') { // to hide mountOptions.password and the likes
      tmp[k] = {};
      Object.keys(v).forEach(function (j) {
        if (v[j] !== SECRET_PLACEHOLDER) tmp[k][j] = v[j];
      });
    } else {
      if (backupConfig[k] !== SECRET_PLACEHOLDER) tmp[k] = v;
    }
  });

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

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

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

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

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

  backups.value = result;
}

onMounted(async () => {
  await refresh();
  busy.value = false;

  autoBackupsEnabled.value = props.app.enableBackup;
});

</script>

<template>

  <div>
    <AppRestoreDialog ref="cloneDialog"/>
    <AppImportDialog ref="importDialog"/>
    <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>
        <div class="info-row">
          <div class="info-label">{{ $t('backups.backupDetails.id') }}</div>
          <div class="info-value">{{ editBackup.id }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ $t('backups.backupEdit.remotePath') }}</div>
          <div class="info-value">{{ editBackup.emotePath }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ $t('backups.backupDetails.date') }}</div>
          <div class="info-value">{{ prettyLongDate(editBackup.creationTime) }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ $t('backups.backupDetails.version') }}</div>
          <div class="info-value">{{ editBackup.packageVersion }}</div>
        </div>
        <div class="info-row">
          <div class="info-label">{{ $t('backups.backupDetails.format') }}</div>
          <div class="info-value">{{ editBackup.format }}</div>
        </div>

        <form @submit.prevent="onEditSubmit()" autocomplete="off">
          <fieldset :disabled="editBusy">
            <p class="has-error" v-show="editError">{{ editError }}</p>

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

            <br/>

            <Checkbox v-model="editPersist" :label="$t('backups.backupEdit.preserved.description')"/>
          </fieldset>
        </form>
      </div>
    </Dialog>

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

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

    <SettingsItem>
      <FormGroup>
        <label>{{ $t('app.backups.import.title') }}</label>
        <div>{{ $t('app.backups.import.description') }}</div>
      </FormGroup>
      <div style="display: flex; align-items: center">
        <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>
      </div>
    </SettingsItem>

    <hr/>

    <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 @click="onCreate()" :loading="createBusy" :disabled="createBusy || app.taskId || app.error || app.runState === 'stopped'" v-tooltip="app.error ? 'App is in error state' : (app.taskId ? 'Task active' : (app.runState === 'stopped' ? 'App is not running' : ''))">{{ $t('app.backups.backups.createBackupAction') }}</Button>
      </div>
    </SettingsItem>

    <p class="has-error" v-if="errorMessage">{{ errorMessage }}</p>

    <TableView :model="backups" :columns="columns" :busy="busy">
      <template #preserveSecs="backup">
        <Icon icon="fa-solid fa-archive" v-show="backup.preserveSecs === -1" />
      </template>
      <template #creationTime="backup">
        {{ prettyLongDate(backup.creationTime) }} <b v-show="backup.label">({{ backup.label }})</b>
      </template>
      <template #actions="backup">
        <div class="table-actions">
          <ButtonGroup>
            <Button secondary tool small icon="fa-solid fa-pencil-alt" v-if="app.accessLevel === 'admin'" v-tooltip="$t('backups.listing.tooltipEditBackup')" @click="onEdit(backup)"></Button>
            <Button secondary tool small icon="fa-solid fa-download" v-if="backup.format === 'tgz' && app.accessLevel === 'admin'" v-tooltip="$t('app.backups.backups.downloadBackupTooltip')" :href="getDownloadLink(backup)"></Button>
            <Button secondary tool small icon="fa-solid fa-file-alt" v-if="app.accessLevel === 'admin'" v-tooltip="$t('app.backups.backups.downloadConfigTooltip')" @click="onDownloadConfig(backup)"></Button>
            <Button secondary tool small icon="fa-solid fa-clone" v-if="app.accessLevel === 'admin'" v-tooltip="$t('app.backups.backups.cloneTooltip')" @click="onClone(backup)"></Button>
            <Button secondary tool small icon="fa-solid fa-history" :disabled="app.taskId || app.runState === 'stopped'" v-tooltip="$t('app.backups.backups.restoreTooltip')" @click="onRestore(backup)"></Button>
          </ButtonGroup>
        </div>
      </template>
    </TableView>
  </div>
</template>
