import { ApplicationContext, ObjectUtils } from "@sankhyalabs/core";
import { h, Host } from "@stencil/core";
export class SnkEntityList {
  constructor() {
    this._ezListSource = [];
    this.config = undefined;
    this.rightListSlotBuilder = undefined;
    this.maxHeightList = "";
    this.value = undefined;
    this.errorMessage = undefined;
  }
  async reloadList() {
    this.loadListSource();
  }
  observeConfig() {
    var _a, _b;
    (_b = (_a = this._searchElement) === null || _a === void 0 ? void 0 : _a['clearValue']) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  ezListChangeListener(evt) {
    var _a, _b;
    this.errorMessage = undefined;
    const configCopy = ObjectUtils.copy(this.config);
    (_a = (this.getListConfigValue(configCopy))) === null || _a === void 0 ? void 0 : _a.forEach(value => {
      var _a, _b;
      if (value && value.id === ((_a = evt.detail) === null || _a === void 0 ? void 0 : _a.id)) {
        value.check = (_b = evt.detail) === null || _b === void 0 ? void 0 : _b.check;
      }
    });
    this.config = ObjectUtils.copy(configCopy);
    this.valueChanged.emit((_b = this.config) === null || _b === void 0 ? void 0 : _b.value);
  }
  loadListSource() {
    var _a;
    this._ezListSource = [];
    (_a = (this.getListConfigValue(this.config))) === null || _a === void 0 ? void 0 : _a.forEach(value => {
      if (value) {
        this._ezListSource.push({
          label: `${value.id} - ${value.label}`,
          check: value.check,
          id: value.id
        });
      }
    });
  }
  componentDidLoad() {
    var _a, _b, _c, _d, _e;
    let configValue = this.getListConfigValue(this.config);
    let configValueArray = [];
    if (Array.isArray(configValue)) {
      configValueArray = configValue;
    }
    else {
      configValueArray.push((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.members);
    }
    this.config.value = configValueArray;
    this._entityName = (_e = (_d = (_c = this.config) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d.searchContext) === null || _e === void 0 ? void 0 : _e.entity;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this.loadListSource();
  }
  optionLoader(searchArgument) {
    var _a, _b, _c, _d, _e, _f, _g;
    const { mode, argument } = searchArgument;
    if (this._application === undefined) {
      return;
    }
    const searchContext = (_c = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.searchContext) !== null && _c !== void 0 ? _c : {};
    const criteria = (_e = (_d = this.config) === null || _d === void 0 ? void 0 : _d.props) === null || _e === void 0 ? void 0 : _e.criteria;
    const options = Object.assign(Object.assign({ criteria }, searchContext), { entityDescription: (_f = this.config) === null || _f === void 0 ? void 0 : _f.label, entity: this._entityName, useSearchPlus: (_g = this.config.props) === null || _g === void 0 ? void 0 : _g["useSearchPlus"] });
    return this._application.executePreparedSearch(mode, argument, options);
  }
  onEzSearchChange(evt) {
    var _a, _b, _c, _d;
    const newValueIsEmpty = ObjectUtils.isEmptySafetyCheck(evt.detail);
    const hasConfingOnList = (_a = this.getListConfigValue(this.config)) === null || _a === void 0 ? void 0 : _a.find((item) => {
      var _a;
      const itemId = typeof item.id === 'number' ? String(item.id) : item.id;
      return itemId === ((_a = evt.detail) === null || _a === void 0 ? void 0 : _a.value);
    });
    if (newValueIsEmpty || hasConfingOnList) {
      return;
    }
    this.config = Object.assign(Object.assign({}, this.config), { value: [
        ...((_c = (_b = this.config) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : []),
        {
          id: evt.detail.value,
          check: true,
          label: evt.detail.label
        }
      ] });
    this.loadListSource();
    this.value = this.config.value;
    this.valueChanged.emit((_d = this.config) === null || _d === void 0 ? void 0 : _d.value);
  }
  getMessage(key, params) {
    var _a;
    return (_a = this._application) === null || _a === void 0 ? void 0 : _a.messagesBuilder.getMessage(key, params);
  }
  getListConfigValue(config) {
    var _a, _b, _c, _d;
    return (_d = (_b = (_a = config.value) === null || _a === void 0 ? void 0 : _a.elements) !== null && _b !== void 0 ? _b : (_c = config === null || config === void 0 ? void 0 : config.value) === null || _c === void 0 ? void 0 : _c.members) !== null && _d !== void 0 ? _d : config === null || config === void 0 ? void 0 : config.value;
  }
  render() {
    var _a, _b, _c, _d, _e;
    const isSearchPlus = ((_a = this.config.props) === null || _a === void 0 ? void 0 : _a["useSearchPlus"]) == true;
    const TagName = isSearchPlus ? "ez-search-plus" : "ez-search";
    return (h(Host, null, h("ez-tooltip", { active: !this.config.enabled, message: this.config.disabledMessage, type: 'warning' }, h(TagName, { ref: elem => this._searchElement = elem, optionLoader: argument => this.optionLoader(argument), label: (_b = this.config) === null || _b === void 0 ? void 0 : _b.label, enabled: (_c = this.config) === null || _c === void 0 ? void 0 : _c.enabled, onEzChange: evt => this.onEzSearchChange(evt), suppressEmptyOption: true, stopPropagateEnterKeyEvent: true }), ((_d = this._ezListSource) === null || _d === void 0 ? void 0 : _d.length) > 0 && (h("label", { class: "label" }, this.getMessage("snkEntityList.selected"))), h("div", { style: this.maxHeightList ? { 'max-height': this.maxHeightList } : {}, class: { "snk-entity-list--overflow": !!this.maxHeightList } }, h("ez-list", { ref: (el) => this._ezList = el, id: "snkEntityList", enabled: (_e = this.config) === null || _e === void 0 ? void 0 : _e.enabled, listMode: "check", dataSource: this._ezListSource, hoverFeedback: true, itemSlotBuilder: this.rightListSlotBuilder, onEzCheckChange: evt => this.ezListChangeListener(evt) })), this.errorMessage &&
      h("span", { class: 'ez-text ez-text--small ez-text--error ez-margin-horizontal--medium' }, this.errorMessage))));
  }
  static get is() { return "snk-entity-list"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-entity-list.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-entity-list.css"]
    };
  }
  static get properties() {
    return {
      "config": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkFilterItemConfig",
          "resolved": "SnkFilterItemConfig",
          "references": {
            "SnkFilterItemConfig": {
              "location": "import",
              "path": "../snk-filter-bar/filter-item/snk-filter-item"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Configura\u00E7\u00F5es para carregar os dados do componente"
        }
      },
      "rightListSlotBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "(item: ListItem, group?: ListGroup) => HTMLElement | string",
          "resolved": "(item: ListItem, group?: ListGroup) => string | HTMLElement",
          "references": {
            "ListItem": {
              "location": "import",
              "path": "../snk-filter-bar/filter-list/snk-filter-list"
            },
            "ListGroup": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/components/ez-list/ez-list"
            },
            "HTMLElement": {
              "location": "global"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "M\u00E9todo que possibilita alterar como o item da lista vai ser apresentado.\nObserva\u00E7\u00E3o: No React ele se transforma em VNode e n\u00E3o HTMLElement."
        }
      },
      "maxHeightList": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Permite definir uma altura m\u00E1xima para o ez-list, adicionando um scroll ao atingir esta medida"
        },
        "attribute": "max-height-list",
        "reflect": false,
        "defaultValue": "\"\""
      },
      "value": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "IOption",
          "resolved": "IOption",
          "references": {
            "IOption": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/components/ez-combo-box/ez-combo-box"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o valor do componente"
        }
      },
      "errorMessage": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Usado para exibir mensagens de erro."
        },
        "attribute": "error-message",
        "reflect": true
      }
    };
  }
  static get states() {
    return {
      "_ezListSource": {}
    };
  }
  static get events() {
    return [{
        "method": "valueChanged",
        "name": "valueChanged",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emite um evento customizado ao realizar altera\u00E7\u00E3o nos valores do componente"
        },
        "complexType": {
          "original": "CustomEvent",
          "resolved": "CustomEvent<any>",
          "references": {
            "CustomEvent": {
              "location": "global"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "reloadList": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "config",
        "methodName": "observeConfig"
      }];
  }
}
