import { r as registerInstance, h, H as Host, c as createEvent } from './index-ecdfb761.js';
import { D as DataTransferField } from './data-transfer-field-2f305919.js';
import { T as TextField } from './index-150b6a59.js';
import { S as SubFormField } from './index-09efdc01.js';
import { S as SingleChoiceField } from './index-23baeeef.js';
import { C as ConcealerConditional, E as Equal } from './Equal-8818d86d.js';
import './index-61dcd269.js';
import { L as ListFetchState } from './list-fetch-state-e772aa74.js';
import { R as RawDataField } from './raw-data-eb55820e.js';
import { D as DateField } from './date-1bc489bd.js';
import { D as DataModel } from './data-model-88af49fc.js';
import './BaseField-0b01dc2c.js';
import './FieldGenerator-3ae403b2.js';
import './InterceptorHandler-6474bcf4.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) {
    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 (h(Host, null, h("doldurma-form", { fields: [
        new DataTransferField('_id')
          .setValue(item === null || item === void 0 ? void 0 : item._id),
        new 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 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 TextField('indexPagePath', 'Index page path', '', 'Used as SPAs\' index page when the root URL is called.')
          .addInterceptor('onFormChange', new ConcealerConditional(new Equal('type', 'website-host')))
          .setVisibility(false)
          .setValue(values.indexPagePath)
          .require(),
        new TextField('errorPagePath', 'Error page path', '', 'Used as SPAs\' error page when a file is not found.')
          .addInterceptor('onFormChange', new ConcealerConditional(new 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 SubFormField('responseHeaders', 'Response Headers', [
          new TextField('name', '', 'Header Name (e.g. Authorization, Content-Type)')
            .require(),
          new 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 ConcealerConditional(new 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) {
    registerInstance(this, hostRef);
    this.list = 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 (h(Host, { class: "container d-flex flex-grow-1 flex-column" }, 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 TextField('domain', 'Domain'),
        new TextField('version', 'Version'),
        new DateField('_created', 'Creation Date'),
        new 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) {
    registerInstance(this, hostRef);
    this.dismissFileExplorer = 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 (h(Host, { class: "container d-flex flex-grow-1 flex-column" }, h("div", { class: "d-flex mb-3" }, h("div", { class: "flex-grow-1 d-flex align-items-center", style: { cursor: 'pointer' } }, h("div", { class: "mr-1", onClick: () => this.dismissFileExplorer.emit() }, h("dvn-icon", { iconName: "uil-estate" })), h("div", { onClick: () => this.navigateToPath(-1) }, item.domain), path.split('/').map((p, i) => (h("div", { onClick: () => this.navigateToPath(i) }, "/", p)))), this.isVersioningEnabled() &&
      h("div", { class: "d-flex align-items-center" }, "Live Version: ", item.version, " \u00A0", this.versionList.isPending &&
        h("dvn-progress", { indefinite: true, tint: "primary", scale: "small" }), 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 => (h("dvn-select-option", { value: option }, option)))))), 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 TextField('name', 'File'),
      ], items: (list.data || []).sort((a, b) => a.localeCompare(b)).map(name => 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();

export { SepetBucketForm as sepet_bucket_form, SepetBucketList as sepet_bucket_list, SepetFileExplorer as sepet_file_explorer };
