<script setup>

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

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

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

const minMemoryLimit = ref(1024 * 1024 * 1024); // 1 GB
const maxMemoryLimit = ref(minMemoryLimit.value); // set later

const dialog = useTemplateRef('dialog');
const site = ref({});
const formError = ref({});
const busy = ref(false);
const name = ref('');
const enableForUpdates = ref(false);
const memoryLimit = ref(0);
const uploadPartSize = ref(0);
const syncConcurrency = ref(0);
const downloadConcurrency = ref(0);
const copyConcurrency = ref(0);
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.setName(site.value.id, name.value);
  if (error) {
    formError.value.generic = error.body ? error.body.message : 'Internal error';
    busy.value = false;
    return console.error(error);
  }

  [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') {
    contents = { exclude: contentExclude.value };
  } else if (includeExclude.value === 'include' && contentInclude.value.length) {
    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);
  }

  const limits = {
    memoryLimit: parseInt(memoryLimit.value),
    uploadPartSize: parseInt(uploadPartSize.value),
    syncConcurrency: parseInt(syncConcurrency.value),
    downloadConcurrency: parseInt(downloadConcurrency.value),
    copyConcurrency: parseInt(copyConcurrency.value),
  };

  [error] = await backupSitesModel.setLimits(site.value.id, limits);
  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;
}

async function getMemory() {
  const [error, result]  = await systemModel.memory();
  if (error) return console.error(error);

  maxMemoryLimit.value = Math.ceil(result.memory / (1024*1024*1024)) * 1024 * 1024 * 1024;
}

defineExpose({
  async open(t) {
    formError.value = {};
    busy.value = false;
    site.value = t;

    name.value = t.name || '';
    enableForUpdates.value = !!t.enableForUpdates;
    memoryLimit.value = t.limits.memoryLimit || 1024 * 1024 * 1024; // 1 GB
    uploadPartSize.value = t.limits.uploadPartSize || 10 * 1024 * 1024;
    syncConcurrency.value = t.limits.syncConcurrency || 10;
    downloadConcurrency.value = t.limits.downloadConcurrency || 10;
    copyConcurrency.value = t.limits.copyConcurrency || 10;

    await getMemory();

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

    contentOptions.value = [{
      id: 'box',
      label: 'Platform',
    }];

    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;
      }
    } else {
      includeExclude.value = 'everything';
    }

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

</script>

<template>
  <Dialog ref="dialog"
    :title="$t('backups.configureBackupStorage.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>
        <form @submit.prevent="onSubmit()" autocomplete="off" ref="form">
          <fieldset :disabled="busy">
            <input style="display: none;" type="submit"/>

            <FormGroup>
              <label for="backupSiteNameInput">{{ $t('backups.configureBackupStorage.name') }}</label>
              <TextInput id="backupSiteNameInput" v-model="name" required/>
            </FormGroup>

            <FormGroup>
              <label>{{  $t('backups.configureBackupStorage.backupContents.title') }}</label>
              <div>{{ $t('backups.configureBackupStorage.backupContents.description') }}</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'" :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'" :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>

            <FormGroup>
              <label for="memoryLimitInput">{{ $t('backups.configureBackupStorage.memoryLimit') }}: <b>{{ prettyBinarySize(memoryLimit, '1024 MB') }}</b></label>
              <div class="small">{{ $t('backups.configureBackupStorage.memoryLimitDescription') }}</div>
              <input type="range" id="memoryLimitInput" v-model="memoryLimit" :step="256*1024*1024" :min="minMemoryLimit" :max="maxMemoryLimit" />
            </FormGroup>

            <FormGroup v-if="s3like(site.provider)">
              <label for="uploadPartSizeInput">{{ $t('backups.configureBackupStorage.uploadPartSize') }}: <b>{{ prettyBinarySize(uploadPartSize, 'Default (50 MiB)') }}</b></label>
              <p class="small">{{ $t('backups.configureBackupStorage.uploadPartSizeDescription') }}</p>
              <input type="range" id="uploadPartSizeInput" v-model="uploadPartSize" list="uploadPartSizeTicks" :step="1024*1024" :min="10*1024*1024" :max="1024*1024*1024" />
              <datalist id="uploadPartSizeTicks">
                <option :value="1024*1024*10"></option>
                <option :value="1024*1024*64"></option>
                <option :value="1024*1024*128"></option>
                <option :value="1024*1024*256"></option>
                <option :value="1024*1024*512"></option>
                <option :value="1024*1024*1024"></option>
              </datalist>
            </FormGroup>

            <FormGroup v-if="site.format === 'rsync'">
              <label for="syncConcurrencyInput">{{ $t('backups.configureBackupStorage.uploadConcurrency') }}: <b>{{ syncConcurrency }}</b></label>
              <div class="small">{{ $t('backups.configureBackupStorage.uploadConcurrencyDescription') }}</div>
              <input type="range" id="syncConcurrencyInput" v-model="syncConcurrency" step="10" min="10" max="200" />
            </FormGroup>

            <FormGroup v-if="site.format === 'rsync' && (s3like(site.provider) || site.provider === 'gcs')">
              <label for="downloadConcurrencyInput">{{ $t('backups.configureBackupStorage.downloadConcurrency') }}: <b>{{ downloadConcurrency }}</b></label>
              <div class="small">{{ $t('backups.configureBackupStorage.downloadConcurrencyDescription') }}</div>
              <input type="range" id="downloadConcurrencyInput" v-model="downloadConcurrency" step="10" min="10" max="200" />
            </FormGroup>

            <FormGroup v-if="site.format === 'rsync' && (s3like(site.provider) || site.provider === 'gcs')">
              <label for="copyConcurrencyInput">{{ $t('backups.configureBackupStorage.copyConcurrency') }}: <b>{{ copyConcurrency }}</b></label>
              <div class="small">{{ $t('backups.configureBackupStorage.copyConcurrencyDescription') }}
                <span v-show="site.provider === 'digitalocean-spaces'">{{ $t('backups.configureBackupStorage.copyConcurrencyDigitalOceanNote') }}</span>
              </div>
              <input type="range" id="copyConcurrencyInput" v-model="copyConcurrency" step="10" min="10" max="500" />
            </FormGroup>
          </fieldset>
        </form>
      </div>
    </div>
  </Dialog>
</template>
