<script setup>

import { ref, useTemplateRef, watch } from 'vue';
import { Dialog, FormGroup, TextInput, PasswordInput, Button, Checkbox } from '@cloudron/pankow';
import { prettyBinarySize } from '@cloudron/pankow/utils';
import { REGIONS_CONTABO, REGIONS_VULTR, REGIONS_IONOS, REGIONS_OVH, REGIONS_LINODE, REGIONS_SCALEWAY, REGIONS_WASABI } from '../constants.js';
import { mountlike, s3like } from  '../utils.js';
import BackupProviderForm from './BackupProviderForm.vue';
import BackupSitesModel from '../models/BackupSitesModel.js';
import SystemModel from '../models/SystemModel.js';

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

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

const dialog = useTemplateRef('dialog');
const form = useTemplateRef('form');
const step = ref('storage');
const newSiteId = ref('');
const name = ref('');
const useEncryption = ref(false);
const encryptionPassword = ref('');
const encryptionPasswordRepeat = ref('');
const encryptedFilenames = ref(false);
const encryptionPasswordHint = ref('');
const formError = ref({});
const busy = ref(false);
const provider = ref('');
const providerConfig = ref({
  mountOptions: {},
  prefix: '',
});
const limits = ref({});
const format = ref('');

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

async function onSubmit() {
  if (!form.value.reportValidity()) return;

  // TODO define good default
  const schedulePattern = '00 00 2,23,11,7,8 * * 3,5,6,0';
  const retention = { keepWithinSecs: 7 * 24 * 60 * 60 };

  // build provider config
  const data = {};
  if (s3like(provider.value)) {
    data.endpoint = providerConfig.value.endpoint;
    data.prefix = providerConfig.value.prefix;
    data.bucket = providerConfig.value.bucket;
    data.accessKeyId = providerConfig.value.accessKeyId;
    data.secretAccessKey = providerConfig.value.secretAccessKey;

    if (provider.value === 's3') {
      data.region = providerConfig.value.region || undefined;
      delete data.endpoint;
    } else if (provider.value === 'minio' || provider.value === 's3-v4-compat') {
      data.region = providerConfig.value.region || 'us-east-1';
      data.acceptSelfSignedCerts = providerConfig.value.acceptSelfSignedCerts;
      data.s3ForcePathStyle = true;
    } else if (provider.value === 'exoscale-sos') {
      data.region = 'us-east-1';
      data.signatureVersion = 'v4';
    } else if (provider.value === 'wasabi') {
      data.region = REGIONS_WASABI.find(function (x) { return x.value === data.endpoint; }).region;
      data.signatureVersion = 'v4';
    } else if (provider.value === 'scaleway-objectstorage') {
      data.region = REGIONS_SCALEWAY.find(function (x) { return x.value === data.endpoint; }).region;
      data.signatureVersion = 'v4';
    } else if (provider.value === 'linode-objectstorage') {
      data.region = REGIONS_LINODE.find(function (x) { return x.value === data.endpoint; }).region;
      data.signatureVersion = 'v4';
    } else if (provider.value === 'ovh-objectstorage') {
      data.region = REGIONS_OVH.find(function (x) { return x.value === data.endpoint; }).region;
      data.signatureVersion = 'v4';
    } else if (provider.value === 'ionos-objectstorage') {
      data.region = REGIONS_IONOS.find(function (x) { return x.value === data.endpoint; }).region;
      data.signatureVersion = 'v4';
    } else if (provider.value === 'vultr-objectstorage') {
      data.region = REGIONS_VULTR.find(function (x) { return x.value === data.endpoint; }).region;
      data.signatureVersion = 'v4';
    } else if (provider.value === 'contabo-objectstorage') {
      data.region = REGIONS_CONTABO.find(function (x) { return x.value === data.endpoint; }).region;
      data.signatureVersion = 'v4';
      data.s3ForcePathStyle = true;
    } else if (provider.value === 'upcloud-objectstorage') { // the UI sets region and endpoint
      const m = /^.*\.(.*)\.upcloudobjects.com$/.exec(data.endpoint);
      data.region = m ? m[1] : 'us-east-1'; // let it fail in validation phase if m is not valid
      data.signatureVersion = 'v4';
    } else if (provider.value === 'digitalocean-spaces') {
      data.region = 'us-east-1';
    } else if (provider.value === 'hetzner-objectstorage') {
      data.region = 'us-east-1';
      data.signatureVersion = 'v4';
    }
  } else if (mountlike(provider.value)) {
    data.prefix = providerConfig.value.prefix;
    data.noHardlinks = !providerConfig.value.useHardlinks;
    data.mountOptions = {};

    if (provider.value === 'cifs' || provider.value === 'sshfs' || provider.value === 'nfs') {
      data.mountOptions.host = providerConfig.value.mountOptionHost;
      data.mountOptions.remoteDir = providerConfig.value.mountOptionRemoteDir;

      if (provider.value === 'cifs') {
        data.mountOptions.username = providerConfig.value.mountOptionUsername;
        data.mountOptions.password = providerConfig.value.mountOptionPassword;
        data.mountOptions.seal = !!providerConfig.value.mountOptionSeal;
        data.preserveAttributes = !!providerConfig.value.preserveAttributes;
      } else if (provider.value === 'sshfs') {
        data.mountOptions.user = providerConfig.value.mountOptionUser;
        data.mountOptions.port = parseInt(providerConfig.value.mountOptionPort);
        data.mountOptions.privateKey = providerConfig.value.mountOptionPrivateKey;
        data.preserveAttributes = true;
      }
    } else if (provider.value === 'ext4' || provider.value === 'xfs' || provider.value === 'disk') {
        data.mountOptions.diskPath = providerConfig.value.mountOptionDiskPath;
        data.preserveAttributes = true;
    } else if (provider.value === 'mountpoint') {
        data.mountPoint = providerConfig.value.mountPoint;
        data.chown = !!providerConfig.value.chown;
        data.preserveAttributes = !!providerConfig.value.preserveAttributes;
    }
  } else if (provider.value === 'filesystem') {
    data.backupDir = providerConfig.value.backupDir;
    data.noHardlinks = !providerConfig.value.useHardlinks;
    data.preserveAttributes = true;
  } else if (provider.value === 'gcs') {
    data.bucket = providerConfig.value.bucket;
    data.prefix = providerConfig.value.prefix;
    data.projectId = providerConfig.value.projectId;
    data.credentials = providerConfig.value.credentials;
  }

  // build limits
  const limitsConfig = {
    memoryLimit: parseInt(limits.value.memoryLimit),
    syncConcurrency: parseInt(limits.value.syncConcurrency),
    copyConcurrency: parseInt(limits.value.copyConcurrency),
    downloadConcurrency: parseInt(limits.value.downloadConcurrency),
    uploadPartSize: parseInt(limits.value.uploadPartSize),
    // deleteConcurrency: parseInt(providerConfig.value.limits.deleteConcurrency),
  };

  formError.value = {};
  busy.value = true;
  const [error, result] = await backupSitesModel.add(name.value, format.value, provider.value, data, schedulePattern, retention, limitsConfig);
  if (error) {
    formError.value.generic = error.body ? error.body.message : 'Internal error';
    busy.value = false;
    return console.error(error);
  }

  // stash for encryption password step
  newSiteId.value = result;

  busy.value = false;
  formError.value = {};

  // signal to refresh the list already
  emit('success');

  if (useEncryption.value) {
    step.value = 'encryption';
  } else {
    dialog.value.close();
  }
}

function isSetupEncryptionFormValid() {
  return encryptionPassword.value && encryptionPassword.value === encryptionPasswordRepeat.value;
}

async function onSetupEncryption() {
  if (!isSetupEncryptionFormValid()) return;

  busy.value = true;

  const [error] = await backupSitesModel.setEncryption(newSiteId.value, encryptionPassword.value, encryptedFilenames.value, encryptionPasswordHint.value);
  if (error) {
    if (error.body && error.body.message.indexOf('password') === 0) {
      formError.value.password = error.body.message;
    } else {
      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;
}

watch(encryptionPassword, () => {
  formError.value.password = null;
});

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

function onCancel() {
  dialog.value.close();
}

defineExpose({
  async open() {
    step.value = 'storage';

    formError.value = {};
    busy.value = false;
    name.value = '';
    provider.value = '';
    format.value = '';
    providerConfig.value = {};
    useEncryption.value = false;
    encryptionPassword.value = '';
    encryptionPasswordRepeat.value = '';
    encryptionPasswordHint.value = '';
    encryptedFilenames.value = false;
    limits.value = {};

    // some sane defaults
    limits.value.memoryLimit = 1024 * 1024 * 1024; // 1 GB
    limits.value.uploadPartSize = 10 * 1024 * 1024;
    limits.value.syncConcurrency = 10;
    limits.value.downloadConcurrency = 10;
    limits.value.copyConcurrency = 10;

    // ensure we have all required child objects
    // needs translation for UI
    providerConfig.value.mountOptions = {};
    providerConfig.value.useHardlinks = false;
    providerConfig.value.encryptionPassword = null;

    await getMemory();

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

</script>

<template>
  <Dialog ref="dialog" :title="$t('backups.target.addDialog.title')">
    <div>
      <div v-if="step === 'storage'">
        <form @submit.prevent="onSubmit()" autocomplete="off" ref="form">
          <fieldset :disabled="busy">
            <input style="display: none;" type="submit"/>

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

            <BackupProviderForm v-model:provider="provider" v-model:format="format" v-model:provider-config="providerConfig" :form-error="formError"/>

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

            <FormGroup v-if="s3like(provider)">
              <label for="uploadPartSizeInput">{{ $t('backups.configureBackupStorage.uploadPartSize') }}: <b>{{ prettyBinarySize(limits.uploadPartSize, 'Default (50 MiB)') }}</b></label>
              <p class="small">{{ $t('backups.configureBackupStorage.uploadPartSizeDescription') }}</p>
              <input type="range" id="uploadPartSizeInput" v-model="limits.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="format === 'rsync' && provider !== 'noop'">
              <label for="syncConcurrencyInput">{{ $t('backups.configureBackupStorage.uploadConcurrency') }}: <b>{{ limits.syncConcurrency }}</b></label>
              <div class="small">{{ $t('backups.configureBackupStorage.uploadConcurrencyDescription') }}</div>
              <input type="range" id="syncConcurrencyInput" v-model="limits.syncConcurrency" step="10" min="10" max="200" />
            </FormGroup>

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

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

            <div style="display: flex; justify-content: space-between; align-items: end; margin-top: 10px">
              <Checkbox v-if="provider !== 'noop'" v-model="useEncryption" label="Use backup encryption"/>

              <div style="display: flex; gap: 6px; align-items: end;">
                <Button secondary :disabled="busy" @click="onCancel()">{{ $t('main.dialog.cancel') }}</Button>
                <Button primary :disabled="busy" :loading="busy" @click="onSubmit()">{{ useEncryption ? $t('main.action.next') : $t('main.dialog.save') }}</Button>
              </div>
            </div>
          </fieldset>
        </form>
      </div>

      <div v-else>
        <form @submit.prevent="onSetupEncryption()" autocomplete="off" ref="encryptionForm">
          <fieldset :disabled="busy">
            <input style="display: none;" type="submit"/>

            <div class="warning-label">{{ $t('backups.configureBackupStorage.encryptionDescription') }}</div>
            <div class="error-label" v-if="formError.generic">{{ formError.generic }}</div>
            <FormGroup>
              <label for="encryptionPassswordInput">{{ $t('backups.configureBackupStorage.encryptionPassword') }} <sup><a href="https://docs.cloudron.io/backups/#encryption" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>
              <PasswordInput id="encryptionPassswordInput" v-model="encryptionPassword" :placeholder="$t('backups.configureBackupStorage.encryptionPasswordPlaceholder')" required />
              <div class="error-label" v-if="formError.password">{{ formError.password }}</div>
            </FormGroup>
            <FormGroup>
              <label for="encryptionPassswordRepeatInput">{{ $t('backups.configureBackupStorage.encryptionPasswordRepeat') }}</label>
              <PasswordInput id="encryptionPassswordRepeatInput" v-model="encryptionPasswordRepeat" required />
              <div class="error-label" v-if="encryptionPasswordRepeat && encryptionPassword !== encryptionPasswordRepeat">{{ $t('profile.changePassword.errorPasswordsDontMatch') }}</div>
            </FormGroup>
            <FormGroup>
              <label for="encryptionPassswordHintInput">{{ $t('backups.configureBackupStorage.encryptionHint') }}</label>
              <TextInput id="encryptionPassswordHintInput" v-model="encryptionPasswordHint" />
            </FormGroup>
            <Checkbox v-if="format === 'rsync'" v-model="encryptedFilenames" :label="$t('backups.configureBackupStorage.encryptFilenames')"/>
            <div style="display: flex; gap: 6px; align-items: end; justify-content: end; margin-top: 10px;">
              <Button secondary :disabled="busy" @click="onCancel()">{{ $t('main.dialog.cancel') }}</Button>
              <Button primary :disabled="busy || !isSetupEncryptionFormValid()" :loading="busy" @click="onSetupEncryption()">{{ $t('main.dialog.save') }}</Button>
            </div>
          </fieldset>
        </form>
      </div>
    </div>
  </Dialog>
</template>
