<script setup>

import { ref, useTemplateRef } from 'vue';
import { Checkbox, Radiobutton, MultiSelect, Dialog, FormGroup } from '@cloudron/pankow';
import AppsModel from '../models/AppsModel.js';
import BackupSitesModel from '../models/BackupSitesModel.js';

const emit = defineEmits([ 'success' ]);

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

const dialog = useTemplateRef('dialog');
const site = ref({});
const provider = ref('');
const formError = ref({});
const busy = ref(false);
const enableForUpdates = ref(false);
const includeExclude = ref('everything'); // or include, exclude
const contentOptions = ref([]);
const contentInclude = ref([]);
const contentExclude = ref([]);

async function onSubmit() {
  busy.value = true;

  let [error] = await backupSitesModel.setEnableForUpdates(site.value.id, enableForUpdates.value);
  if (error) {
    formError.value.generic = error.body ? error.body.message : 'Internal error';
    busy.value = false;
    return console.error(error);
  }

  let contents;
  if (includeExclude.value === 'everything') {
    contents = null;
  } else if (includeExclude.value === 'exclude') {
    if (contentExclude.value.length === 0) {
      formError.value.includeExclude = 'Exclude at least one content item or select Everything';
      busy.value = false;
      return;
    }

    contents = { exclude: contentExclude.value };
  } else if (includeExclude.value === 'include') {
    if (contentInclude.value.length === 0) {
      formError.value.includeExclude = 'Include at least one content item';
      busy.value = false;
      return;
    }

    contents = { include: contentInclude.value };
  }

  [error] = await backupSitesModel.setContents(site.value.id, contents);
  if (error) {
    formError.value.generic = error.body ? error.body.message : 'Internal error';
    busy.value = false;
    return console.error(error);
  }

  emit('success');
  dialog.value.close();
  busy.value = false;
}

defineExpose({
  async open(t) {
    t = JSON.parse(JSON.stringify(t)); // make a copy

    formError.value = {};
    busy.value = false;
    site.value = t;
    provider.value = t.provider;
    includeExclude.value = 'everything';
    contentInclude.value = [];
    contentExclude.value = [];

    enableForUpdates.value = !!t.enableForUpdates;

    const [error, result] = await appsModel.list();
    if (error) return console.error(error);

    contentOptions.value = [{
      id: 'box',
      label: 'System & email',
    }];

    result.forEach(a => {
      contentOptions.value.push({
        id: a.id,
        label: `${a.label || a.fqdn} - ${a.manifest.title}`,
      });
    });

    if (t.contents !== null) {
      if (t.contents.exclude) {
        includeExclude.value = 'exclude';
        contentExclude.value = t.contents.exclude;
      } else if (t.contents.include) {
        includeExclude.value = 'include';
        contentInclude.value = t.contents.include;
      }
    }

    dialog.value.open();
  }
});

</script>

<template>
  <Dialog ref="dialog"
    :title="$t('backups.configureContent.title')"
    :reject-label="$t('main.dialog.close')"
    :reject-active="!busy"
     reject-style="secondary"
    :confirm-label="$t('main.dialog.save')"
    :confirm-busy="busy"
     confirm-style="primary"
    @confirm="onSubmit()"
  >
    <div>
      <div>
        <p>{{ $t('backups.configureBackupStorage.backupContents.context', { name: site.name }) }}</p>

        <div class="error-label" v-if="formError.generic">{{ formError.generic }}</div>

        <form @submit.prevent="onSubmit()" autocomplete="off" ref="form">
          <fieldset :disabled="busy">
            <input style="display: none;" type="submit"/>

            <FormGroup>
              <label>{{  $t('backups.configureBackupStorage.backupContents.title') }}</label>
              <div>{{ $t('backups.configureBackupStorage.backupContents.description') }}</div>
              <div class="error-label" v-if="formError.includeExclude">{{ formError.includeExclude }}</div>
              <div style="padding-top: 10px">
                <Radiobutton v-model="includeExclude" value="everything" :label="$t('backups.configureBackupStorage.backupContents.everything')"/>
                <Radiobutton v-model="includeExclude" value="exclude" :label="$t('backups.configureBackupStorage.backupContents.excludeSelected')"/>
                <MultiSelect v-model="contentExclude" v-if="includeExclude === 'exclude'" required :options="contentOptions" :search-threshold="10" option-key="id" style="margin: 6px 0 6px 25px;"/>
                <Radiobutton v-model="includeExclude" value="include" :label="$t('backups.configureBackupStorage.backupContents.includeOnlySelected')"/>
                <MultiSelect v-model="contentInclude" v-if="includeExclude === 'include'" required :options="contentOptions" :search-threshold="10" option-key="id" style="margin: 6px 0 6px 25px;"/>
              </div>
            </FormGroup>

            <FormGroup>
              <label>{{ $t('backups.configureBackupStorage.automaticUpdates.title') }}</label>
              <div description>{{ $t('backups.configureBackupStorage.automaticUpdates.description') }}</div>
              <Checkbox v-model="enableForUpdates" :label="$t('backups.configureBackupStorage.useForUpdates')" />
            </FormGroup>
          </fieldset>
        </form>
      </div>
    </div>
  </Dialog>
</template>
