import { ElementIDUtils, ObjectUtils } from '@sankhyalabs/core';
import { ApplicationUtils } from "@sankhyalabs/ezui/dist/collection/utils";
import { Fragment, h, Host } from '@stencil/core';
import { PersonalizedFilterUtils } from '../../snk-personalized-filter/subcomponents/snk-filter-param-config/utils/PersonalizedFilterUtils';
import { EPresentationMode } from './editors/enum/presentationMode';
import FilterItemType from './filter-item-type.enum';
export class SnkFilterDetail {
  constructor() {
    this.config = undefined;
    this.getMessage = undefined;
    this.showHardFixed = true;
    this.removalBlocked = false;
  }
  /**
   * Define o foco no campo do editor.
   */
  async setFocusField() {
    var _a, _b, _c, _d;
    if (!this._editor) {
      return;
    }
    if (this._editor["setFocus"]) {
      (_b = (_a = this._editor) === null || _a === void 0 ? void 0 : _a["setFocus"]) === null || _b === void 0 ? void 0 : _b.call(_a);
    }
    else if (this._editor["focus"]) {
      (_d = (_c = this._editor) === null || _c === void 0 ? void 0 : _c["focus"]) === null || _d === void 0 ? void 0 : _d.call(_c);
    }
  }
  async clearValue() {
    if (!this._editor) {
      return;
    }
    if (this._editor["clearValue"]) {
      await this._editor["clearValue"]();
    }
  }
  observeConfig(newValue) {
    var _a, _b;
    this._editor && (this._editor["config"] = newValue);
    (_b = (_a = this._editor) === null || _a === void 0 ? void 0 : _a["reloadList"]) === null || _b === void 0 ? void 0 : _b.call(_a);
    this._customElementObject = this.getContentEditor();
  }
  componentDidLoad() {
    if (this._element) {
      ElementIDUtils.addIDInfo(this._element);
      const dataElementIdDoFilterItem = this._element.getAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME);
      this._idContentEditor = `${dataElementIdDoFilterItem}_${this.config.id}`;
    }
  }
  changeConfig(newConfig) {
    this.filterChange.emit(newConfig);
  }
  getContentEditor() {
    switch (this.config.type) {
      case FilterItemType.BINARY_SELECT:
        return { tag: "snk-filter-binary-select" };
      case FilterItemType.MULTI_SELECT:
        return { tag: "snk-filter-multi-select" };
      case FilterItemType.PERIOD:
        return { tag: "snk-filter-period" };
      case FilterItemType.SEARCH:
        return { tag: "snk-filter-search" };
      case FilterItemType.NUMBER:
        return { tag: "snk-filter-number" };
      case FilterItemType.PERSONALIZED:
        const snkFilterPersonalizedProps = {
          tag: "snk-personalized-filter-editor", props: {
            presentationMode: EPresentationMode.CHIP,
            onValueChanged: evt => this.handleValueChanged(evt),
          }
        };
        return snkFilterPersonalizedProps;
      case FilterItemType.CHECK_BOX_LIST:
        return {
          tag: "snk-filter-checkbox-list",
          props: {
            onValueChanged: evt => this.config = Object.assign(Object.assign({}, this.config), { value: evt.detail })
          }
        };
      case FilterItemType.MULTI_LIST:
        return {
          tag: "snk-entity-list",
          props: {
            onValueChanged: evt => this.config = Object.assign(Object.assign({}, this.config), { value: evt.detail })
          }
        };
    }
    return { tag: "snk-filter-text" };
  }
  handleValueChanged({ detail }) {
    const groupedItems = (detail === null || detail === void 0 ? void 0 : detail.items) || this.config.groupedItems;
    this.config = Object.assign(Object.assign({}, this.config), { groupedItems, visible: (groupedItems || []).filter(item => item.visible).length > 0 });
  }
  removeItem() {
    const hasMultiValues = this.config.type === FilterItemType.MULTI_LIST && Array.isArray(this.config.value);
    const newValue = hasMultiValues ? this.config.value.map((valueItem) => (Object.assign(Object.assign({}, valueItem), { check: false }))) : undefined;
    const removedConfig = Object.assign(Object.assign({}, this.config), { visible: false, fixed: false, value: newValue });
    if (removedConfig.groupedItems != undefined) {
      removedConfig.groupedItems = removedConfig.groupedItems.map(item => (Object.assign(Object.assign({}, item), { visible: false, fixed: false, value: undefined })));
    }
    this.changeConfig(removedConfig);
  }
  removeItemFromGroup(item) {
    return Object.assign(Object.assign({}, item), { visible: false, fixed: false, value: undefined });
  }
  getPopUpHeaderButtons() {
    return (h(Fragment, null, !this.removalBlocked && !this.config.removalBlocked &&
      this.buildIcon(this.getMessage("snkFilterBar.removeFilter"), "delete", () => this.removeItem()), this.showHardFixed && !this.config.hardFixed &&
      this.buildIcon(this.getMessage(this.config.fixed ? "snkFilterBar.unpinFilter" : "snkFilterBar.pinFilter"), this.config.fixed ? "un-pin" : "push-pin", () => this.changeConfig(Object.assign(Object.assign({}, this.config), { fixed: !this.config.fixed })))));
  }
  buildIcon(title, iconName, action) {
    return (h("button", { onClick: () => action(), class: "sc-snk-filter-bar snk-filter-item__editor-header-button", ref: elem => elem && this.buildIdButton(elem, title) }, h("ez-icon", Object.assign({ title: title, iconName: iconName }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${ElementIDUtils.getInternalIDInfo(`_${title}`)}` }))));
  }
  buildIdButton(buttonElement, title) {
    if (!buttonElement)
      return;
    const dataElement = { id: title };
    buttonElement.removeAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME);
    ElementIDUtils.addIDInfoIfNotExists(buttonElement, "button", dataElement);
  }
  clearBinarySelectValues() {
    var _a;
    const editor = this._editor || {};
    (_a = editor.resetValues) === null || _a === void 0 ? void 0 : _a.call(editor);
    this.config = ObjectUtils.copy(this.originalConfig);
    this.changeConfig(Object.assign(Object.assign({}, this.config), { value: undefined }));
  }
  apply() {
    const isValid = PersonalizedFilterUtils.validateVariableValues(this.config, this._editor["value"]);
    if (!isValid) {
      return ApplicationUtils.alert(this.getMessage('snkFilterBar.filterModal.validations.notFullFilled.title'), this.getMessage('snkFilterBar.filterModal.validations.notFullFilled.message'));
    }
    const valuesArray = this._editor["value"] !== undefined ? this._editor["value"] : this.config.value;
    this.changeConfig(Object.assign(Object.assign({}, this.config), { visible: this.isVisible(), value: valuesArray }));
  }
  isVisible() {
    if (this.config.groupedItems && this.config.groupedItems.length > 0) {
      return this.config.groupedItems.filter(item => item.visible).length > 0;
    }
    return true;
  }
  clear() {
    var _a;
    if (this.config.type === FilterItemType.BINARY_SELECT) {
      this.clearBinarySelectValues();
      return;
    }
    if (FilterItemType.MULTI_LIST === this.config.type) {
      const configCopy = ObjectUtils.copy(this.config);
      (_a = configCopy.value) === null || _a === void 0 ? void 0 : _a.forEach(value => !!value && (value.check = false));
      this.config = ObjectUtils.copy(configCopy);
      return;
    }
    this.changeConfig(Object.assign(Object.assign({}, this.config), { value: undefined }));
  }
  filterCanBeCleared() {
    return this.config.type !== FilterItemType.PERSONALIZED;
  }
  onKeyDonwListener(event) {
    if (event.key === "Enter") {
      this.apply();
    }
  }
  buildRightSlot(item) {
    return h("ez-icon", { iconName: "delete", onClick: () => this.removeValueFromConfig(item) });
  }
  removeValueFromConfig(item) {
    var _a, _b;
    if (this.config) {
      const configCopy = ObjectUtils.copy(this.config);
      const index = (_a = configCopy.value) === null || _a === void 0 ? void 0 : _a.findIndex(i => (i === null || i === void 0 ? void 0 : i.id) === item.id);
      (_b = configCopy.value) === null || _b === void 0 ? void 0 : _b.splice(index, 1);
      this.config = ObjectUtils.copy(configCopy);
    }
  }
  componentWillLoad() {
    this.originalConfig = ObjectUtils.copy(this.config);
    this._customElementObject = this.getContentEditor();
  }
  render() {
    const { tag: CustomElement, props } = this._customElementObject;
    return (h(Host, null, h("div", { class: "col ez-col--sd-12 ez-align--right ez-padding-medium ez-flex--align-items-center" }, h("div", { class: "ez-text ez-title ez-title--small ez-padding--small sc-snk-filter-bar snk-filter-item__editor-header" }, this.config.detailTitle), this.getPopUpHeaderButtons()), h(CustomElement, Object.assign({ maxHeightList: '240px', ref: ref => this._editor = ref, value: this.config.value, config: this.config, onKeyDown: evt => this.onKeyDonwListener(evt), "data-element-id": this._idContentEditor, getMessage: this.getMessage, rightListSlotBuilder: item => this.buildRightSlot(item) }, props)), h("hr", { class: "sc-snk-filter-bar snk-filter__popover-rule" }), h("div", { class: "ez-col ez-col--sd-12 ez-align--right" }, this.filterCanBeCleared() && (h("ez-button", { label: this.getMessage("snkFilterBar.cleanFilter"), onClick: () => this.clear(), size: "small" })), h("ez-button", { ref: ref => this._applyButton = ref, label: this.getMessage("snkFilterBar.applyFilter"), onClick: () => this.apply(), size: "small", class: "ez-button--primary ez-padding-left--medium" }))));
  }
  static get is() { return "snk-filter-detail"; }
  static get properties() {
    return {
      "config": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkFilterItemConfig",
          "resolved": "SnkFilterItemConfig",
          "references": {
            "SnkFilterItemConfig": {
              "location": "import",
              "path": "./snk-filter-item"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define as configura\u00E7\u00F5es do componente snk-filter-detail."
        }
      },
      "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."
        }
      },
      "showHardFixed": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Controla a visibilidade do bot\u00E3o de fixar elemento"
        },
        "attribute": "show-hard-fixed",
        "reflect": false,
        "defaultValue": "true"
      },
      "removalBlocked": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o filtro pode ser removido."
        },
        "attribute": "removal-blocked",
        "reflect": false,
        "defaultValue": "false"
      }
    };
  }
  static get events() {
    return [{
        "method": "filterChange",
        "name": "filterChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando h\u00E1 uma altera\u00E7\u00E3o nos filtros."
        },
        "complexType": {
          "original": "SnkFilterItemConfig",
          "resolved": "SnkFilterItemConfig",
          "references": {
            "SnkFilterItemConfig": {
              "location": "import",
              "path": "./snk-filter-item"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "setFocusField": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Define o foco no campo do editor.",
          "tags": []
        }
      },
      "clearValue": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
  static get watchers() {
    return [{
        "propName": "config",
        "methodName": "observeConfig"
      }];
  }
}
