import { r as registerInstance, h, H as Host } from './index-b6f10a81.js';
import './data-model-bb5789f5.js';
import { L as ListFetchState } from './list-fetch-state-8615484c.js';

function buildSort(query) {
  if (query && query.sort) {
    return query.sort;
  }
  return undefined;
}
function buildQuery(query, quickFilter) {
  let queryFilter = query ? query.filter : undefined;
  if (quickFilter) {
    if (query && query.filter) {
      queryFilter = {
        operator: 'and',
        filters: [query.filter, quickFilter]
      };
    }
    else {
      queryFilter = quickFilter;
    }
  }
  return queryFilter;
}

const DvnAppViewListViewCard = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.list = ListFetchState.init();
  }
  async invalidate(_event) {
    this.list = ListFetchState.init();
  }
  ;
  fetchList(ignoreError = false) {
    const { list, quickFilter } = this;
    if (list.isPending || list.isEndReached() || (list.error && !ignoreError)) {
      return;
    }
    const { query, table } = this.view;
    this.list = list.beforeFetch();
    const queryFilter = buildQuery(query, quickFilter);
    this.apiData.query(table.name, {
      fields: query.fields,
      filter: queryFilter,
      limit: 25,
      skip: list.data ? list.data.length : 0,
      sort: buildSort(query),
    }).then(response => {
      this.list = list.afterFetch(response);
    }, error => {
      this.list = list.afterFetchError(error);
    });
  }
  componentWillLoad() {
    this.fetchList();
  }
  render() {
    const { list, view } = this;
    return (h(Host, null, h("div", { class: "mt-3 pt-3" }, list.data &&
      h("dvn-card-list-view", { config: view.ui, fields: view.table.fields, items: list.data }), list.error &&
      h("devingen-error-card", { error: list.error, message: "Fetching list failed.", onRetry: () => this.fetchList(true) }))));
  }
};

export { DvnAppViewListViewCard as dvn_app_view_list_view_card };
