import { ArrayUtils, ElementIDUtils, FloatingManager } from '@sankhyalabs/core';
import { h, Host } from '@stencil/core';
const SHOW_MORE_ITEM_NAME = "__SHOWMORE__";
const MAX_FILTERS = 5;
export class SnkFilterList {
  constructor() {
    this._preselection = -1;
    this.innerClickCheck = (_floatingContainer, node) => {
      if (node.id != FloatingManager.MODAL_ELEMENT_ID) {
        return true;
      }
      this._detailIsVisible = false;
      return false;
    };
    this._filterArgument = undefined;
    this._showAll = undefined;
    this.label = undefined;
    this.iconName = undefined;
    this.items = undefined;
    this.getMessage = undefined;
    this.emptyText = undefined;
    this.findFilterText = undefined;
    this.buttonClass = undefined;
  }
  showDetail() {
    this._preselection = -1;
    this._floatingID = FloatingManager.float(this._popover, this._popoverContainer, {
      autoClose: true,
      innerClickTest: this.innerClickCheck,
      backClickListener: () => this.onListCloseCallback(),
      useOverlay: true
    });
    this._detailIsVisible = true;
    this._showAll = false;
    this._filterArgument = "";
    this._filterInput.setFocus();
  }
  /**
   * Oculta os detalhes do componente snk-filter-list.
   */
  async hideDetail() {
    if (this._floatingID != undefined) {
      FloatingManager.close(this._floatingID);
    }
  }
  onListCloseCallback() {
    this._floatingID = undefined;
    this._detailIsVisible = false;
  }
  buttonClick() {
    if (this._detailIsVisible) {
      this.hideDetail();
    }
    else {
      this.showDetail();
    }
  }
  componentDidLoad() {
    if (this._element) {
      ElementIDUtils.addIDInfo(this._element);
    }
  }
  componentDidRender() {
    if (this._floatingID == undefined) {
      if (this._popover) {
        this._popover.remove();
      }
    }
  }
  buildIdElement(buttonElement, name) {
    if (!buttonElement)
      return;
    const dataElement = { id: name };
    buttonElement.removeAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME);
    ElementIDUtils.addIDInfoIfNotExists(buttonElement, "filterItemList", dataElement);
  }
  buildItemElement(item) {
    const itemId = ++this._selectableItemsCount;
    return (h("button", { ref: elem => elem && this.buildIdElement(elem, item.label), id: `filter-item${itemId}`, onFocusin: () => this._preselection = itemId, class: `ez-col ez-col--sd-12 ez-align--middle ez-padding--small sc-snk-filter-bar snk-filter-bar__filter-list-item`, onClick: () => this.itemSelected(item.name), name: item.label, key: itemId }, item.iconName ? h("ez-icon", { iconName: item.iconName, size: "small", class: `ez-padding-right--extra-small sc-snk-filter-bar snk-filter-bar__filter-list-item__icon ${item.iconClass || ""}` }) : undefined, h("div", { class: `ez-text ez-text--medium ez-text--primary ez-padding--extra-small sc-snk-filter-bar snk-filter-bar__filter-list-item__label ${item.labelClass || ""}` }, item.label)));
  }
  itemSelected(itemName) {
    if (itemName === SHOW_MORE_ITEM_NAME) {
      this._showAll = true;
    }
    else {
      this.hideDetail();
      this.snkItemSelected.emit(itemName);
    }
  }
  getFilterItems() {
    const items = this.items ? ArrayUtils.applyStringFilter(this._filterArgument, this.items.filter(item => item.kind === "FILTER")) : [];
    if (items.length === 0) {
      return h("div", { class: "ez-text ez-text--medium ez-text--primary ez-padding--extra-small sc-snk-filter-bar snk-filter-bar__filter-list-items-container--empty" }, this.emptyText);
    }
    const hideItems = !this._filterArgument && !this._showAll && (items.length > MAX_FILTERS + 1);
    if (hideItems) {
      items.splice(MAX_FILTERS);
      items.push({ kind: "INTERNAL", label: this.getMessage("snkFilterList.showMore"), iconName: "dots-horizontal", name: SHOW_MORE_ITEM_NAME, iconClass: "snk-filter-bar__filter-list-item__icon--secondary", labelClass: "snk-filter-bar__filter-list-item__label--secondary" });
    }
    this._selectableItemsCount = 0;
    return h("div", { class: "sc-snk-filter-bar snk-filter-bar__filter-list-items-container" }, items.map(item => this.buildItemElement(item)));
  }
  getFooterItems() {
    return this.items.filter(item => item.kind === "FOOTER");
  }
  keyDownHandler(event) {
    switch (event.key) {
      case "ArrowDown":
        this.changePreselection(this._preselection + 1);
        //Paramos a propagação do evento para evitar scroll indesejado
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();
        break;
      case "ArrowUp":
        this.changePreselection(this._preselection - 1);
        //Paramos a propagação do evento para evitar scroll indesejado
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();
        break;
    }
  }
  changePreselection(newSelection) {
    if (newSelection < 0) {
      newSelection = this._selectableItemsCount;
    }
    this._preselection = newSelection > this._selectableItemsCount ? 0 : newSelection;
    if (this._preselection === 0) {
      this._filterInput.setFocus();
    }
    else {
      const item = this._element.querySelector(`#filter-item${this._preselection}`);
      if (item) {
        item.focus();
      }
    }
  }
  render() {
    return (h(Host, { class: "ez-flex ez-flex--column" }, h("ez-button", { class: this.buttonClass, label: this.label, onClick: () => this.buttonClick(), mode: this.iconName ? "icon" : undefined, iconName: this.iconName, size: "small" }, h("slot", { name: "leftIcon" })), h("section", { class: "ez-margin-top--small sc-snk-filter-bar snk-filter__popover-container", ref: elem => this._popoverContainer = elem }, h("div", { class: "sc-snk-filter-bar snk-filter__popover ez-padding--small ez-elevation--4", ref: elem => this._popover = elem }, h("ez-filter-input", { ref: ref => this._filterInput = ref, "data-element-id": "serachFilters", mode: "slim", label: this.findFilterText, value: this._filterArgument, onEzChange: (evt) => this._filterArgument = evt.detail, onFocus: () => this._preselection = 0 }), this.getFilterItems(), h("hr", { class: "sc-snk-filter-bar snk-filter__popover-rule" }), this.items ? this.getFooterItems().map(item => this.buildItemElement(item)) : undefined))));
  }
  static get is() { return "snk-filter-list"; }
  static get properties() {
    return {
      "label": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o label usado no ez-button do filtro."
        },
        "attribute": "label",
        "reflect": false
      },
      "iconName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o \u00EDcone usado no ez-button do filtro."
        },
        "attribute": "icon-name",
        "reflect": false
      },
      "items": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Array<ListItem>",
          "resolved": "ListItem[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "ListItem": {
              "location": "local"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Guarda a lista de filtros."
        }
      },
      "getMessage": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "(key: string, props?: any) => string",
          "resolved": "(key: string, props?: any) => string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Usado pra flexibilizar os verbetes e mensagens de acordo com o SnkMessageBuilder."
        }
      },
      "emptyText": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o texto exibido quando a lista est\u00E1 vazia."
        },
        "attribute": "empty-text",
        "reflect": false
      },
      "findFilterText": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o texto exibido no componente de busca."
        },
        "attribute": "find-filter-text",
        "reflect": false
      },
      "buttonClass": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a classe CSS a ser adicionada no bot\u00E3o (usado principalmente para sinalizar o filtro aplicado)."
        },
        "attribute": "button-class",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "_filterArgument": {},
      "_showAll": {}
    };
  }
  static get events() {
    return [{
        "method": "snkItemSelected",
        "name": "snkItemSelected",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Disparado quando um item da lista \u00E9 clicado."
        },
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "hideDetail": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Oculta os detalhes do componente snk-filter-list.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
  static get listeners() {
    return [{
        "name": "keydown",
        "method": "keyDownHandler",
        "target": undefined,
        "capture": true,
        "passive": false
      }];
  }
}
