import { r as registerInstance, c as createEvent, h, H as Host } from './index-55faf181.js';
import { g as generateDefaultFilters } from './util-c68b7c9b.js';
import { a as generateActionComponent } from './action-util-c91834e1.js';
import { L as ListFetchState } from './list-fetch-state-623a5ba4.js';
import { r as replaceParamsInFilter, c as cloneFilter } from './filter-8542e288.js';
import './filter-cbaa3d7d.js';
import './data-model-f5160369.js';

const dvnAppViewListViewTableCss = ".sc-dvn-app-view-list-view-table-h{-ms-flex:1 1 1px;flex:1 1 1px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;margin:calc(4 * var(--spacing-unit));overflow:hidden}.leaned-horizontally.sc-dvn-app-view-list-view-table-h{margin-left:0;margin-right:0}.leaned-vertically.sc-dvn-app-view-list-view-table-h{margin-bottom:0;margin-top:0}.sc-dvn-app-view-list-view-table-h h2.sc-dvn-app-view-list-view-table{margin:0;line-height:1.2em}.sc-dvn-app-view-list-view-table-h h2.sc-dvn-app-view-list-view-table:before{content:\"\";display:block;height:0;width:0;margin-top:calc(calc(1 - 1.2) * 0.5em)}.sc-dvn-app-view-list-view-table-h dvn-filter-simple.sc-dvn-app-view-list-view-table{-ms-flex:1;flex:1}.sc-dvn-app-view-list-view-table-h .header-actions-container.sc-dvn-app-view-list-view-table dvn-button.sc-dvn-app-view-list-view-table{--margin:0 calc(1.5 * var(--spacing-unit))}.sc-dvn-app-view-list-view-table-h .table-container.sc-dvn-app-view-list-view-table{-ms-flex:1 1 1px;flex:1 1 1px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;overflow:hidden}";

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;
}
const DvnAppViewListViewTable = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.action = createEvent(this, "action", 7);
    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 = ui.quickSearch ? generateDefaultFilters(ui.quickSearch, table.fields) : undefined;
    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("div", { class: "d-flex align-items-center pt-3 pb-3" }, h("h2", null, title), h("div", { class: "header-actions-container d-flex flex-grow-1 align-items-center justify-content-end pl-3" }, 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 }))));
  }
};
DvnAppViewListViewTable.style = dvnAppViewListViewTableCss;

export { DvnAppViewListViewTable as dvn_app_view_list_view_table };
