import { Fragment, h, Host } from '@stencil/core';
import { ApplicationUtils } from '@sankhyalabs/ezui/dist/collection/utils';
export class PesquisaTree {
  constructor() {
    this.treeLoader = undefined;
    this.argument = undefined;
    this.allowsNonAnalytic = false;
    this.shouldLoadTree = false;
    this.messagesBuilder = undefined;
    this.items = [];
  }
  async applyFilter() {
    await this._tree.applyFilter(this.argument);
  }
  async observeShouldLoadTree(newValue) {
    if (!newValue || this.items.length > 0)
      return;
    await this.loadTree();
  }
  async loadTree() {
    if (!this.shouldLoadTree)
      return;
    if (!this.treeLoader || typeof this.treeLoader !== 'function')
      return;
    const response = await this.treeLoader((this.argument || '').trim());
    this.items = [...response];
  }
  expandOrCloseAllItems(items, expanded) {
    return items.map(item => (Object.assign(Object.assign({}, item), { expanded, children: item.children ? this.expandOrCloseAllItems(item.children, expanded) : undefined })));
  }
  handleExpandAll() {
    this.items = [...this.expandOrCloseAllItems(this.items, true)];
  }
  handleCloseAll() {
    this.items = [...this.expandOrCloseAllItems(this.items, false)];
  }
  handleDbClick(item) {
    var _a;
    if (!this.allowsNonAnalytic && !((_a = item['props']) === null || _a === void 0 ? void 0 : _a['analitico'])) {
      const title = this.getMessage('snkPesquisa.tree.errorTitle');
      const message = this.getMessage('snkPesquisa.tree.nonAnalyticError');
      ApplicationUtils.error(title, message);
      return;
    }
    const option = {
      value: item.id,
      label: item.label,
    };
    this.pesquisaTreeSelectItem.emit(option);
  }
  renderEmptyMessage() {
    return (h("div", { class: "ez-flex ez-flex--justify-center ez-flex--align-items-center ez-margin--large ez-text ez-text--xlarge ez-text--secondary" }, h("span", null, this.getMessage('snkPesquisa.tree.emptyMessage'))));
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  render() {
    var _a;
    return (h(Host, null, !((_a = this.items) === null || _a === void 0 ? void 0 : _a.length) ?
      this.renderEmptyMessage() :
      h(Fragment, null, h("div", { class: 'actions-container' }, h("ez-button", { size: 'small', mode: 'icon', class: 'ez-margin-right--small', iconName: 'show-list', title: this.getMessage('snkPesquisa.tree.expandButton'), onClick: () => this.handleExpandAll() }), h("ez-button", { size: 'small', mode: 'icon', iconName: 'hide-list', title: this.getMessage('snkPesquisa.tree.collapseButton'), onClick: () => this.handleCloseAll() })), h("ez-tree", { ref: (element) => this._tree = element, onEzDbClickItem: ({ detail }) => this.handleDbClick(detail), items: this.items }))));
  }
  static get is() { return "pesquisa-tree"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["pesquisa-tree.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["pesquisa-tree.css"]
    };
  }
  static get properties() {
    return {
      "treeLoader": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "(text: string) => Promise<Array<ITreeItem>>",
          "resolved": "(text: string) => Promise<ITreeItem[]>",
          "references": {
            "Promise": {
              "location": "global"
            },
            "Array": {
              "location": "global"
            },
            "ITreeItem": {
              "location": "import",
              "path": "@sankhyalabs/ezui/src/components/ez-tree/interfaces/ITreeItem"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Fun\u00E7\u00E3o respons\u00E1vel por carregar a \u00E1rvore hier\u00E1rquica do componente"
        }
      },
      "argument": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Argumentos que ser\u00E3o usados ao chamar a fun\u00E7\u00E3o treeLoader."
        },
        "attribute": "argument",
        "reflect": false
      },
      "allowsNonAnalytic": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se permite sele\u00E7\u00E3o de items n\u00E3o anal\u00EDticos"
        },
        "attribute": "allows-non-analytic",
        "reflect": false,
        "defaultValue": "false"
      },
      "shouldLoadTree": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Informa se a \u00E1rvore hier\u00E1rquica deve ou n\u00E3o ser carregada."
        },
        "attribute": "should-load-tree",
        "reflect": false,
        "defaultValue": "false"
      },
      "messagesBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Respons\u00E1vel por flexibilizar e padronizar o uso de mensagens nos blocos de constru\u00E7\u00E3o."
        }
      }
    };
  }
  static get states() {
    return {
      "items": {}
    };
  }
  static get events() {
    return [{
        "method": "pesquisaTreeSelectItem",
        "name": "pesquisaTreeSelectItem",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IOption",
          "resolved": "IOption",
          "references": {
            "IOption": {
              "location": "import",
              "path": "@sankhyalabs/ezui/src/components/ez-search/ez-search"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "applyFilter": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "shouldLoadTree",
        "methodName": "observeShouldLoadTree"
      }];
  }
}
