'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-1141a245.js');
const dataTransferField = require('./data-transfer-field-e8417d5f.js');
const index$2 = require('./index-61f9621a.js');
const index$3 = require('./index-9fd84b93.js');
const index$1 = require('./index-9d3d3d15.js');
const Equal = require('./Equal-e7239026.js');
require('./index-2eea69a0.js');
const listFetchState = require('./list-fetch-state-6f8f3bf8.js');
const rawData = require('./raw-data-34f1739c.js');
const date = require('./date-a24d7714.js');
const dataModel = require('./data-model-01c368bc.js');
require('./BaseField-381327a9.js');
require('./FieldGenerator-279a646b.js');
require('./InterceptorHandler-09a1e84b.js');

function convertBucketToFormValues(item) {
  if (!item) {
    return {
      indexPagePath: 'index.html',
      errorPagePath: 'index.html',
      responseHeaders: [
        { name: 'Cache-Control', value: 'no-cache' }
      ]
    };
  }
  return {
    domain: item.domain,
    indexPagePath: item.indexPagePath,
    errorPagePath: item.errorPagePath,
    isCacheEnabled: item.isCacheEnabled,
    versionIdentifier: item.versionIdentifier,
    responseHeaders: Object.entries(item.responseHeaders || {}).map(([name, value]) => ({ name, value }))
  };
}
function convertFormValuesToBucket(values) {
  // simple folders don't have the website host related fields
  if (values.type === 'simple-folder') {
    return {
      domain: values.domain,
      indexPagePath: '',
      errorPagePath: '',
      isCacheEnabled: false,
      versionIdentifier: 'path',
      region: 'eu-central-1'
    };
  }
  const responseHeaders = {};
  (values.responseHeaders || []).forEach(({ name, value }) => {
    responseHeaders[name] = value;
  });
  return {
    domain: values.domain,
    indexPagePath: values.indexPagePath,
    errorPagePath: values.errorPagePath,
    isCacheEnabled: true,
    versionIdentifier: 'header',
    responseHeaders,
    region: 'eu-central-1'
  };
}

const SepetBucketForm = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.onSubmitForm = (event) => {
      const { values } = event.detail;
      const body = convertFormValuesToBucket(values);
      const promise = values._id
        ? this.apiSepet.updateBucket(values._id, body)
        : this.apiSepet.createBucket(body);
      this.isPending = true;
      promise.then(this.onChange)
        .catch(error => {
        var _a;
        this.formErrors = [(_a = error.data) === null || _a === void 0 ? void 0 : _a.error];
      })
        .finally(() => this.isPending = false);
    };
  }
  render() {
    const { formErrors, isPending, item } = this;
    const values = convertBucketToFormValues(item);
    return (index.h(index.Host, null, index.h("doldurma-form", { fields: [
        new dataTransferField.DataTransferField('_id')
          .setValue(item === null || item === void 0 ? void 0 : item._id),
        new index$1.SingleChoiceField('type', 'Bucket type', [
          { label: 'Simple File Storage', value: 'simple-folder' },
          { label: 'Static Website Host', value: 'website-host' },
        ], '', 'select', '')
          .setDisabled(!!(item === null || item === void 0 ? void 0 : item._id))
          .setValue(values.versionIdentifier === 'header' ? 'website-host' : 'simple-folder')
          .require(),
        new index$2.TextField('domain', 'Domain', '', 'Used in the URL like \'acme\' for \'acme.sepet.devingen.io\'')
          .setValue(values.domain)
          .setDisabled(!!(item === null || item === void 0 ? void 0 : item._id))
          .require(),
        new index$2.TextField('indexPagePath', 'Index page path', '', 'Used as SPAs\' index page when the root URL is called.')
          .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('type', 'website-host')))
          .setVisibility(false)
          .setValue(values.indexPagePath)
          .require(),
        new index$2.TextField('errorPagePath', 'Error page path', '', 'Used as SPAs\' error page when a file is not found.')
          .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('type', 'website-host')))
          .setVisibility(false)
          .setValue(values.errorPagePath)
          .require(),
        // new BooleanField('isCacheEnabled', 'Is cache enabled?', '', 'Cache the file in CDN for subsequent requests.')
        //   .addInterceptor('onFormChange', new ConcealerConditional(new Equal('type', 'website-host')))
        //   .setVisibility(false)
        //   .setValue(values.isCacheEnabled),
        new index$3.SubFormField('responseHeaders', 'Response Headers', [
          new index$2.TextField('name', '', 'Header Name (e.g. Authorization, Content-Type)')
            .require(),
          new index$2.TextField('value', '', 'Header Value')
            .require(),
        ], 'HTTP response headers returned by CDN to get file responses. Useful for browser cache management.')
          .setMaxCount(10)
          .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('type', 'website-host')))
          .setVisibility(false)
          .setValue(values.responseHeaders)
      ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending, formErrors: formErrors })));
  }
};

const SepetBucketList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.list = listFetchState.ListFetchState.init();
  }
  componentWillLoad() {
    this.fetchList();
  }
  async fetchList() {
    const { list } = this;
    this.list = this.list.beforeFetch();
    const response = await this.apiSepet.getBuckets().catch(error => {
      this.list = list.afterFetchError(error);
    });
    if (!response)
      return;
    this.list = list.afterFetch(response, false);
  }
  render() {
    const { list } = this;
    return (index.h(index.Host, { class: "container d-flex flex-grow-1 flex-column" }, index.h("dvn-list-view-table", { config: {
        actions: [
          {
            ui: {
              name: 'open',
              buttonType: 'icon-button',
              iconName: 'uil uil-folder',
              view: 'flat',
              tint: 'neutral',
            },
          },
          {
            ui: {
              name: 'edit',
              buttonType: 'icon-button',
              iconName: 'uil uil-pen',
              view: 'flat',
            },
          },
          {
            ui: {
              name: 'delete',
              buttonType: 'icon-button',
              iconName: 'uil uil-trash',
              view: 'flat',
              tint: 'danger',
            },
          },
        ],
        fields: [
          { fieldId: 'domain' },
          { fieldId: 'version' },
          { fieldId: '_created' },
          { fieldId: '_id' },
        ]
      }, fields: [
        new index$2.TextField('domain', 'Domain'),
        new index$2.TextField('version', 'Version'),
        new date.DateField('_created', 'Creation Date'),
        new rawData.RawDataField('_id', 'ID'),
      ], items: (list.data || []).sort((a, b) => a.domain.localeCompare(b.domain)), isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchList(), scrollToFit: true })));
  }
};

const SepetFileExplorer = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.dismissFileExplorer = index.createEvent(this, "dismissFileExplorer", 7);
    this.versionList = FileListFetchState.init();
    this.list = FileListFetchState.init();
    this.selectedVersion = '';
    this.path = '';
    this.navigateToPath = (index) => {
      if (index === -1) {
        this.path = '';
      }
      else {
        this.path = this.path.split('/').slice(0, index + 1).join('/') + '/';
      }
      this.fetchFileList();
    };
    this.isVersioningEnabled = () => this.item.versionIdentifier === 'header';
  }
  componentWillLoad() {
    if (this.item.versionIdentifier === 'header') {
      this.fetchVersionList();
    }
    else {
      this.fetchFileList();
    }
  }
  onAction(event) {
    event.stopImmediatePropagation();
    const action = event.detail;
    switch (action.name) {
      case 'open': {
        const file = action.params.item;
        if (file.name.lastIndexOf('.') > file.name.lastIndexOf('/')) {
          // open the file in new tab
          if (this.item.versionIdentifier === 'path') {
            window.open(`https://${this.item.domain}.sepet.devingen.io/${this.selectedVersion}/${this.path}${file.name}`, '_blank').focus();
          }
          else {
            window.open(`https://${this.item.domain}.sepet.devingen.io/${this.path}${file.name}`, '_blank').focus();
          }
          // const fileURL = `http://localhost/${this.path}${file.name}`
          return;
        }
        this.path = `${this.path}${file.name}`;
        this.fetchFileList();
        break;
      }
    }
  }
  async fetchVersionList() {
    const { versionList, item } = this;
    this.list = this.list.beforeFetch();
    this.versionList = FileListFetchState.init();
    this.versionList = this.versionList.beforeFetch();
    const response = await this.apiSepet.getBucketVersionList(item._id).catch(error => {
      this.versionList = versionList.afterFetchError(error);
    });
    if (!response)
      return;
    this.versionList = versionList.afterFetch(response, false);
    this.selectedVersion = this.item.version;
    this.fetchFileList();
  }
  async fetchFileList() {
    const { item, path } = this;
    this.list = FileListFetchState.init();
    this.list = this.list.beforeFetch();
    const version = this.isVersioningEnabled() ? this.selectedVersion : '';
    const response = await this.apiSepet.getFileList(item.domain, path, version).catch(error => {
      this.list = this.list.afterFetchError(error);
    });
    if (!response)
      return;
    this.list = this.list.afterFetch(response, false);
  }
  render() {
    var _a;
    const { item, list, path, selectedVersion } = this;
    return (index.h(index.Host, { class: "container d-flex flex-grow-1 flex-column" }, index.h("div", { class: "d-flex mb-3" }, index.h("div", { class: "flex-grow-1 d-flex align-items-center", style: { cursor: 'pointer' } }, index.h("div", { class: "mr-1", onClick: () => this.dismissFileExplorer.emit() }, index.h("dvn-icon", { iconName: "uil-estate" })), index.h("div", { onClick: () => this.navigateToPath(-1) }, item.domain), path.split('/').map((p, i) => (index.h("div", { onClick: () => this.navigateToPath(i) }, "/", p)))), this.isVersioningEnabled() &&
      index.h("div", { class: "d-flex align-items-center" }, "Live Version: ", item.version, " \u00A0", this.versionList.isPending &&
        index.h("dvn-progress", { indefinite: true, tint: "primary", scale: "small" }), index.h("dvn-select", { key: selectedVersion, value: selectedVersion, disabled: this.versionList.isPending, onChange: (e) => {
          this.selectedVersion = e.detail;
          this.fetchFileList();
        }, width: "100px", leaned: true }, (_a = this.versionList.data) === null || _a === void 0 ? void 0 : _a.sort((a, b) => b.localeCompare(a)).map(option => (index.h("dvn-select-option", { value: option }, option)))))), index.h("dvn-list-view-table", { config: {
        actionsPlacement: 'left',
        actions: [
          {
            ui: {
              name: 'open',
              buttonType: 'icon-button',
              iconName: 'uil uil-eye',
              view: 'flat',
              tint: 'neutral',
            },
          }
        ],
        fields: [
          { fieldId: 'name' },
        ]
      }, fields: [
        new index$2.TextField('name', 'File'),
      ], items: (list.data || []).sort((a, b) => a.localeCompare(b)).map(name => dataModel.DataModel.decode({
        _id: name,
        name
      })), isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchFileList(), scrollToFit: true })));
  }
};
class FileListFetchState {
  constructor(data, meta, isPending = false, error) {
    this.beforeFetch = () => new FileListFetchState(this.data, this.meta, true, undefined);
    this.afterFetch = (response, append = true) => {
      var _a;
      const data = (this.data && append) ? [...this.data, ...response.results] : response.results;
      let meta = this.meta; // keep existing meta if the later ones don't have total
      if ((_a = response.meta) === null || _a === void 0 ? void 0 : _a.total) {
        meta = response.meta;
      }
      else if (!meta && response.results.length === 0) {
        // generate a meta to indicate that the end is reached when there is no items left
        meta = {
          total: data.length
        };
      }
      return new FileListFetchState(data, meta, false, undefined);
    };
    this.afterFetchError = (error) => new FileListFetchState(this.data, this.meta, false, error);
    this.isEndReached = () => (this.data && this.meta) ? this.data.length >= this.meta.total : false;
    this.data = data;
    this.error = error;
    this.isPending = isPending;
    this.meta = meta;
  }
}
FileListFetchState.init = () => new FileListFetchState();

exports.sepet_bucket_form = SepetBucketForm;
exports.sepet_bucket_list = SepetBucketList;
exports.sepet_file_explorer = SepetFileExplorer;
