import { Component, Event, h, Host, Listen, Prop, State } from '@stencil/core';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { DataModel } from '@dvn/core/models/data-model';
export class SepetFileExplorer {
  constructor() {
    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 })));
  }
  static get is() { return "sepet-file-explorer"; }
  static get properties() { return {
    "apiSepet": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "SepetApi",
        "resolved": "SepetApi",
        "references": {
          "SepetApi": {
            "location": "import",
            "path": "../../api/sepet-api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "item": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Bucket",
        "resolved": "Bucket",
        "references": {
          "Bucket": {
            "location": "import",
            "path": "../../models/bucket"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "versionList": {},
    "list": {},
    "selectedVersion": {},
    "error": {},
    "isPending": {},
    "path": {}
  }; }
  static get events() { return [{
      "method": "dismissFileExplorer",
      "name": "dismissFileExplorer",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get listeners() { return [{
      "name": "action",
      "method": "onAction",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
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();
