<script setup>

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

const appsModel = AppsModel.create();

const dialog = useTemplateRef('dialog');
const backupConfigInput = useTemplateRef('backupConfigInput');
const appId = ref('');
const busy = ref(false);
const formError = ref({});
const providerConfig = ref({});
const provider = ref('');
const fullPath = ref('');
const format = ref('');
const encrypted = ref(false);
const encryptionPasswordHint = ref('');
const encryptionPassword = ref('');
const encryptedFilenames = ref(false);

const form = useTemplateRef('form');
const isFormValid = ref(false);
function checkValidity() {
  isFormValid.value = form.value ? form.value.checkValidity() : false;
}

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

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

  const config = {};

  const { prefix, remotePath } = parseFullBackupPath(fullPath.value);

  // only set provider specific fields, this will clear them in the db
  if (s3like(provider.value)) {
    config.bucket = providerConfig.value.bucket;
    config.prefix = providerConfig.value.prefix;
    config.accessKeyId = providerConfig.value.accessKeyId;
    config.secretAccessKey = providerConfig.value.secretAccessKey;
    config.prefix = prefix;

    if (providerConfig.value.endpoint) config.endpoint = providerConfig.value.endpoint;

    if (provider.value === 's3') {
      if (providerConfig.value.region) config.region = providerConfig.value.region;
      delete config.endpoint;
    } else if (provider.value === 'minio' || provider.value === 's3-v4-compat') {
      config.region = providerConfig.value.region || 'us-east-1';
      config.acceptSelfSignedCerts = !!providerConfig.value.acceptSelfSignedCerts;
      config.s3ForcePathStyle = true; // might want to expose this in the UI
    } else if (provider.value === 'exoscale-sos') {
      config.region = 'us-east-1';
      config.signatureVersion = 'v4';
    } else if (provider.value === 'wasabi') {
      config.region = REGIONS_WASABI.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'scaleway-objectstorage') {
      config.region = REGIONS_SCALEWAY.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'linode-objectstorage') {
      config.region = REGIONS_LINODE.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'ovh-objectstorage') {
      config.region = REGIONS_OVH.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'ionos-objectstorage') {
      config.region = REGIONS_IONOS.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'vultr-objectstorage') {
      config.region = REGIONS_VULTR.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
    } else if (provider.value === 'contabo-objectstorage') {
      config.region = REGIONS_CONTABO.find(function (x) { return x.value === config.endpoint; }).region;
      config.signatureVersion = 'v4';
      config.s3ForcePathStyle = true; // https://docs.contabo.com/docs/products/Object-Storage/technical-description (no virtual buckets)
    } else if (provider.value === 'upcloud-objectstorage') {
      const m = /^.*\.(.*)\.upcloudobjects.com$/.exec(providerConfig.value.endpoint);
      config.region = m ? m[1] : 'us-east-1'; // let it fail in validation phase if m is not valid
      config.signatureVersion = 'v4';
    } else if (provider.value === 'digitalocean-spaces') {
      config.region = 'us-east-1';
    } else if (provider.value === 'hetzner-objectstorage') {
      config.region = 'us-east-1';
      config.signatureVersion = 'v4';
    } else if (provider.value === 'synology-c2-objectstorage') {
      config.region = 'us-east-1';
      config.signatureVersion = 'v4';
    }
  } else if (mountlike(provider.value)) {
    config.prefix = prefix;
    config.noHardlinks = !providerConfig.value.useHardlinks;
    config.mountOptions = {};

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

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

  const data = {
    format: format.value,
    provider: provider.value,
    config,
    remotePath
  };

  if (encrypted.value) {
    data.encryptionPassword = encryptionPassword.value;
    data.encryptedFilenames = encryptedFilenames.value;
  }

  const [error] = await appsModel.import(appId.value, data);
  if (error) {
    busy.value = false;
    formError.value = {};

    if (error.status === 424) {
      formError.value.generic = error.body.message;

      if (error.body.message.indexOf('AWS Access Key Id') !== -1) {
        formError.value.accessKeyId = true;
      } else if (error.body.message.indexOf('not match the signature') !== -1 || error.body.message.indexOf('Signature') !== -1) {
        formError.value.secretAccessKey = true;
      } else if (error.body.message.toLowerCase() === 'access denied') {
        formError.value.accessKeyId = true;
      } else if (error.body.message.indexOf('ECONNREFUSED') !== -1) {
        formError.value.generic = 'Unknown region';
        formError.value.region = true;
      } else if (error.body.message.toLowerCase() === 'wrong region') {
        formError.value.generic = 'Wrong S3 Region';
        formError.value.region = true;
      } else {
        formError.value.bucket = true;
      }
    } else if (error.status === 400) {
      formError.value.generic = error.body.message;

      if (provider.value === 'filesystem') {
        formError.value.backupDir = true;
      }
    } else {
      formError.value.generic = 'Internal error';
      console.error(error);
    }

    return;
  }

  dialog.value.close();
  busy.value = false;
  formError.value = {};

  // clear potential post-install flag
  delete localStorage['confirmPostInstall_' + appId.value];
}

function onBackupConfigChanged(event) {
  const reader = new FileReader();
  reader.onload = function (result) {
    if (!result.target || !result.target.result) return console.error('Unable to read backup config');

    let data;
    try {
      data = JSON.parse(result.target.result); // 'provider', 'config', 'limits', 'format', 'remotePath', 'encrypted', 'encryptedFilenames'
    } catch (e) {
      console.error('Unable to parse backup config', e);
      return;
    }

    provider.value = data.provider;
    if (data.provider === 'filesystem') { // this allows a user to upload a backup to server and import easily with an absolute path
      fullPath.value = data.config.prefix ? `${data.config.backupDir}/${data.config.prefix}/${data.remotePath}` : `${data.config.backupDir}/${data.remotePath}`;
    } else if (data.provider === 'mountpoint') {
      fullPath.value = data.config.prefix ? `${data.config.mountPoint}/${data.config.prefix}/${data.remotePath}` : `${data.config.mountPoint}/${data.remotePath}`;
    } else {
      fullPath.value = data.config.prefix ? `${data.config.prefix}/${data.remotePath}` : data.remotePath;
    }
    format.value = data.format;
    encrypted.value = !!data.encrypted;
    encryptionPasswordHint.value = data.encryptionPasswordHint || '';
    encryptionPassword.value = '';
    encryptedFilenames.value = data.encryptedFilenames;

    providerConfig.value = {};
    for (const [key, value] of Object.entries(data.config)) {
      switch (key) {
      case 'noHardlinks':
      case 'chown':
      case 'preserveAttributes':
        // not really used for importing
        break;
      case 'projectId':
      case 'credentials':
        // gcs fields which should be set by user by uploading json
        break;
      case 'mountOptions': // providerConfig uses a flattened format of config.mountOptions
        providerConfig.value.mountOptionHost = data.config.mountOptions.host;
        providerConfig.value.mountOptionPort = data.config.mountOptions.port;
        providerConfig.value.mountOptionRemoteDir = data.config.mountOptions.remoteDir;
        providerConfig.value.mountOptionSeal = !!data.config.mountOptions.seal;
        providerConfig.value.mountOptionDiskPath = data.config.mountOptions.diskPath;
        providerConfig.value.mountOptionUser = data.config.mountOptions.user;
        providerConfig.value.mountOptionUsername = data.config.mountOptions.username;
        providerConfig.value.mountOptionPassword = data.config.mountOptions.password;
        providerConfig.value.mountOptionPrivateKey = '';
        break;
      case 'accessKeyId': // s3
      case 'secretAccessKey': // s3
      case 'bucket': // s3, gcs
      case 'prefix': // s3, gcs
      case 'signatureVersion': // s3
      case 'endpoint': // s3
      case 'region': // s3
      case 'acceptSelfSignedCerts': // s3
      case 's3ForcePathStyle': // s3
        providerConfig.value[key] = value;
        break;
      default:
        console.log('unhandled key when importing config file:', key);
      }
    }

    setTimeout(checkValidity, 100); // update state of the confirm button
  };

  reader.readAsText(event.target.files[0]);
}

function onUploadBackupConfig() {
  backupConfigInput.value.click();
}

watchEffect(() => {
  if (providerConfig.value.credentials) setTimeout(checkValidity, 100);
});

defineExpose({
  async open(id) {
    appId.value = id;
    busy.value = false;
    formError.value = {};
    provider.value = '';
    providerConfig.value = {};
    fullPath.value = '';
    encrypted.value = false;
    encryptionPassword.value = '';
    encryptedFilenames.value = false;
    encryptionPasswordHint.value = '';

    dialog.value.open();

    setTimeout(checkValidity, 100); // update state of the confirm button
  }
});

</script>

<template>
  <div>
    <input ref="backupConfigInput" type="file" style="display: none" accept="application/json, text/json" @change="onBackupConfigChanged"/>

    <Dialog ref="dialog" :title="$t('app.importBackupDialog.title')"
     :confirm-label="$t('app.importBackupDialog.importAction')"
     :confirm-active="!busy && isFormValid"
     :confirm-busy="busy"
     :reject-label="$t('main.dialog.cancel')"
     :reject-active="!busy"
      reject-style="secondary"
     @confirm="onSubmit()"
    >
      <div>
        <div class="text-danger">{{ $t('app.importBackupDialog.warning') }}</div>

        <!-- ideally, we get can get rid of this and just display this error from the imported config -->
        <p class="text-danger">{{ $t('app.importBackupDialog.versionMustMatchInfo') }}</p>

        <p>{{ $t('app.importBackupDialog.provideBackupInfo') }}
          <input type="file" ref="backupConfigFileInput" @change="onBackupConfigChanged" accept="application/json, text/json" style="display:none"/>
          <button type="button" style="background: none; border: none; color: #007bff; cursor: pointer; text-decoration: underline; padding: 0;" @click="onUploadBackupConfig()">
            {{ $t('app.importBackupDialog.uploadAction') }}
          </button>
        </p>

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

            <!-- remotePath contains the prefix as well -->
            <FormGroup>
              <label for="inputRemotePath">{{ $t('app.importBackupDialog.remotePath') }} <sup><a href="https://docs.cloudron.io/backups/#import-app-backup" class="help" target="_blank"><i class="fa fa-question-circle"></i></a></sup></label>
              <TextInput id="inputRemotePath" v-model="fullPath" required />
            </FormGroup>

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

            <Checkbox v-model="encrypted" :label="$t('backups.configureBackupStorage.usesEncryption')"/>
            <FormGroup v-if="encrypted">
              <label for="encryptionPassswordInput">{{ $t('backups.configureBackupStorage.encryptionPassword') }}</label>
              <PasswordInput id="encryptionPassswordInput" v-model="encryptionPassword" :placeholder="$t('backups.configureBackupStorage.encryptionPasswordPlaceholder')" required/>
              <div class="warning-label" v-if="encryptionPasswordHint">{{ $t('backups.configureBackupStorage.encryptionHint') }}: {{ encryptionPasswordHint }}</div>
            </FormGroup>
            <Checkbox v-if="encrypted && format === 'rsync'" v-model="encryptedFilenames" :label="$t('backups.configureBackupStorage.encryptFilenames')"/>
          </fieldset>
        </form>
      </div>
    </Dialog>
  </div>
</template>
