import { generateDefaultFilters } from '@dvn/alaca/components/dvn-filter-simple/util';
import { buildQuery, buildSort } from '@dvn/core/components/views/dvn-app-view-list-view-card/util';
import { ListFetchState } from '@dvn/core/models/list-fetch-state';
import { Component, Element, h, Host, Method, Prop, State } from '@stencil/core';
export class DvnAppViewListViewCard {
  constructor() {
    this.list = ListFetchState.init();
    this.onSimpleFilterChange = ({ filter }) => {
      this.quickFilter = filter;
      this.fetchList(true, true);
    };
  }
  async invalidate(_event) {
    this.fetchList(true, true);
  }
  ;
  /**
   * This method is called by the parent component when the parent is re-rendering its' content.
   * The list loses the scroll position when the parent is re-rendering so we set the list scroll
   * position manually to retain the last position.
   */
  async retainPosition() {
    const lc = this.el.querySelector(`.list-container`);
    if (lc) {
      lc.scrollTop = this.scrollPosition;
    }
  }
  ;
  componentWillLoad() {
    this.fetchList();
  }
  fetchList(ignoreError = false, invalidate = false) {
    const { list, quickFilter } = this;
    if (list.isPending || (!invalidate && 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);
    });
  }
  render() {
    const { list, view } = this;
    const { ui } = view;
    return (h(Host, null,
      ui.quickSearch &&
        h("dvn-filter-simple", { fields: this.view.table.fields, progressing: list.isPending && !!list.data, config: ui.quickSearch, onFilterChange: (e) => this.onSimpleFilterChange(e.detail) }),
      list.data &&
        h("div", { class: "list-container", onScroll: (e) => {
            const el = e.target;
            this.scrollPosition = el.scrollTop;
            if (el.offsetHeight + el.scrollTop >= el.scrollHeight) {
              this.fetchList();
            }
          } },
          h("dvn-card-list-view", { config: view.ui, fields: view.table.fields, items: list.data }),
          (list.isPending && !ui.quickSearch) &&
            h("div", { class: "d-flex justify-content-center pb-3" },
              h("dvn-progress", { indefinite: true, tint: "primary" }))),
      (list.isPending && !list.data) &&
        h("div", { class: "d-flex justify-content-center" },
          h("dvn-progress", { indefinite: true, tint: "primary" })),
      list.error &&
        h("devingen-error-card", { error: list.error, message: "Fetching list failed.", onRetry: () => this.fetchList(true) })));
  }
  static get is() { return "dvn-app-view-list-view-card"; }
  static get originalStyleUrls() { return {
    "$": ["dvn-app-view-list-view-card.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["dvn-app-view-list-view-card.css"]
  }; }
  static get properties() { return {
    "view": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "CardListViewConfig",
        "resolved": "CardListViewConfig",
        "references": {
          "CardListViewConfig": {
            "location": "import",
            "path": "@dvn/core/models/card-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": ""
      }
    }
  }; }
  static get states() { return {
    "list": {},
    "quickFilter": {}
  }; }
  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": []
      }
    },
    "retainPosition": {
      "complexType": {
        "signature": "() => Promise<void>",
        "parameters": [],
        "references": {
          "Promise": {
            "location": "global"
          }
        },
        "return": "Promise<void>"
      },
      "docs": {
        "text": "This method is called by the parent component when the parent is re-rendering its' content.\nThe list loses the scroll position when the parent is re-rendering so we set the list scroll\nposition manually to retain the last position.",
        "tags": []
      }
    }
  }; }
  static get elementRef() { return "el"; }
}
