import { generateDefaultFilters } from '@dvn/alaca/components/dvn-filter-simple/util';
import { generateActionComponent } from '@dvn/core/components/views/dvn-card-view/action-util';
import { ListFetchState } from '@dvn/core/models/list-fetch-state';
import { cloneFilter, replaceParamsInFilter } from '@dvn/core/util/filter';
import { Component, Event, h, Host, Listen, Method, Prop, State } from '@stencil/core';
function buildQuery(query, quickFilter, params) {
  let queryFilter = query ? query.filter : undefined;
  if (quickFilter) {
    if (query && query.filter) {
      queryFilter = {
        operator: 'and',
        filters: [query.filter, quickFilter]
      };
    }
    else {
      queryFilter = quickFilter;
    }
  }
  if (!queryFilter) {
    return undefined;
  }
  return replaceParamsInFilter(cloneFilter(queryFilter), params);
}
function buildSort(query) {
  if (query && query.sort) {
    return query.sort;
  }
  return undefined;
}
export class DvnAppViewListViewTable {
  constructor() {
    this.list = ListFetchState.init();
    this.getLogger = () => this.logger.new('DvnAppViewListViewTable').setColor('river');
    this.isQuickFilterBlockingFetch = () => { var _a; return ((_a = this.view.ui.quickSearch) === null || _a === void 0 ? void 0 : _a.requireFilters) && !this.quickFilter; };
    this.onSimpleFilterChange = ({ filter }) => {
      // componentDidUpdate will fetch new list after the state is updated
      this.list = ListFetchState.init();
      this.quickFilter = filter;
    };
  }
  async invalidate(_event) {
    this.fetchList(true, true);
  }
  ;
  handleScroll() {
    this.fetchList();
  }
  onModifyItem(event) {
    const { field, item, value } = event.detail;
    this.updateItem(item, field, value);
  }
  componentWillLoad() {
    if (this.isQuickFilterBlockingFetch()) {
      return;
    }
    this.fetchList();
  }
  componentDidUpdate() {
    if (this.isQuickFilterBlockingFetch()) {
      return;
    }
    const { list } = this;
    if (!list.data && !list.isPending && !list.error) {
      this.fetchList();
    }
  }
  fetchList(ignoreError = false, invalidate = false) {
    const { list, quickFilter } = this;
    if (list.isPending || list.isEndReached() || (list.error && !ignoreError)) {
      return;
    }
    const { query, table, ui } = this.view;
    // get the default quick filter value if the fields have preset values
    const defaultQuickFilter = generateDefaultFilters(ui.quickSearch, table.fields);
    const queryFilter = buildQuery(query, quickFilter || defaultQuickFilter, this.params);
    this.list = list.beforeFetch();
    this.apiData.query(table.name, {
      fields: query.fields,
      filter: queryFilter,
      limit: 25,
      skip: invalidate ? 0 : (list.data ? list.data.length : 0),
      sort: buildSort(query),
    }).then(response => {
      this.list = list.afterFetch(response, !invalidate);
    }, error => {
      this.list = list.afterFetchError(error);
    });
  }
  async updateItem(item, field, value) {
    const data = { [field.id]: value };
    const existingData = { [field.id]: item[field.id] };
    // update the item in the list, we'll revert if update fails
    this.list = this.list.afterUpdateItem(item._id, data);
    const revertChange = () => {
      this.getLogger().errorGroup('Failed to update item.', { field, item, value });
      this.notifier.alert('Update failed.');
      this.list = this.list.afterUpdateItem(item._id, existingData);
    };
    const updateBody = {
      operation: 'update',
      data,
    };
    const result = await this.apiData.update(this.view.table.name, item._id, updateBody).catch(revertChange);
    if (!result)
      return;
    this.getLogger().debugGroup('Updated item.', { field, item, value });
  }
  render() {
    const { view: { title, ui } } = this;
    const headerActions = ui.header && ui.header.actions && ui.header.actions;
    const { list } = this;
    return (h(Host, { class: {
        'leaned-vertically': ui.leanedVertically === undefined ? true : ui.leanedVertically,
        'leaned-horizontally': ui.leanedHorizontally === undefined ? true : ui.leanedHorizontally,
      } },
      h("main", { class: "full-page" },
        h("div", { class: "d-flex align-items-center justify-content-between" },
          h("h2", null, title),
          h("div", { class: "d-flex align-items-center" },
            ui.quickSearch &&
              h("dvn-filter-simple", { fields: this.view.table.fields, leaned: headerActions ? headerActions.length % 2 === 0 : true, config: ui.quickSearch, onFilterChange: (e) => this.onSimpleFilterChange(e.detail) }),
            (ui.header && ui.header.actions && ui.header.actions) &&
              ui.header.actions.map((action, _index) => generateActionComponent(0, this.params, undefined, this.action, action)))),
        this.isQuickFilterBlockingFetch() &&
          h("p", { class: "text-centered" }, "You need to apply a filter to fetch data."),
        !this.isQuickFilterBlockingFetch() &&
          h("div", { class: "table-container" },
            h("dvn-list-view-table", { config: ui.main, fields: this.view.table.fields, items: (list.data || []), isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchList(true), params: this.params })))));
  }
  static get is() { return "dvn-app-view-list-view-table"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["dvn-app-view-list-view-table.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["dvn-app-view-list-view-table.css"]
  }; }
  static get properties() { return {
    "view": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "TableListViewConfig",
        "resolved": "TableListViewConfig",
        "references": {
          "TableListViewConfig": {
            "location": "import",
            "path": "@dvn/core/models/table-list-view-config"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "params": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "params",
      "reflect": false
    },
    "apiData": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "DataApi",
        "resolved": "DataApi",
        "references": {
          "DataApi": {
            "location": "import",
            "path": "@dvn/core/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "notifier": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Notifier",
        "resolved": "Notifier",
        "references": {
          "Notifier": {
            "location": "import",
            "path": "@dvn/alaca/global/notifier/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "logger": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Logger",
        "resolved": "Logger",
        "references": {
          "Logger": {
            "location": "import",
            "path": "@dvn/core/log/logger"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "list": {},
    "quickFilter": {}
  }; }
  static get events() { return [{
      "method": "action",
      "name": "action",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get methods() { return {
    "invalidate": {
      "complexType": {
        "signature": "(_event: CustomEvent<InvalidationAction>) => Promise<void>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          },
          "CustomEvent": {
            "location": "global"
          },
          "InvalidationAction": {
            "location": "import",
            "path": "@dvn/core/models/actions"
          }
        },
        "return": "Promise<void>"
      },
      "docs": {
        "text": "",
        "tags": []
      }
    }
  }; }
  static get listeners() { return [{
      "name": "scrollToBottom",
      "method": "handleScroll",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "modifyItem",
      "method": "onModifyItem",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
