import { proxyCustomElement, HTMLElement, createEvent, h, Fragment, Host } from '@stencil/core/internal/client';
import { ElementIDUtils, UserInterface, ApplicationContext } from '@sankhyalabs/core';
import { F as FilterItemType } from './filter-item-type.enum.js';
import { E as EPresentationMode } from './presentationMode.js';
import { EzScrollDirection } from '@sankhyalabs/ezui/dist/collection/components/ez-scroller/EzScrollDirection';
import { CheckMode } from '@sankhyalabs/ezui/dist/collection/utils';

const snkPersonalizedFilterEditorCss = ".sc-snk-personalized-filter-editor-h{--snk-filter-personalized__max-height:21;--snk-filter-personalized__max-width:21.5}.SnkFilterPersonalized_list-container.sc-snk-personalized-filter-editor{margin:0;padding:0;list-style:none;display:flex;flex-direction:column}.SnkFilterPersonalized_list-container-chip.sc-snk-personalized-filter-editor{width:400px}.SnkFilterPersonalized_list-scroller.sc-snk-personalized-filter-editor{display:block;max-height:calc(var(--space--2xl) * var(--snk-filter-personalized__max-height));cursor:auto;--ez-scroller__max-height:300px}.SnkFilterPersonalized_checkbox.sc-snk-personalized-filter-editor{display:grid;grid-template-columns:auto auto;justify-content:start}.SnkFilterPersonalized_list-container.sc-snk-personalized-filter-editor:has(.SnkFilterPersonalized_list-item--chip){gap:var(--space--small, 6px);max-width:calc(var(--space--md) * var(--snk-filter-personalized__max-width))}.SnkFilterPersonalized_list-item--modal.sc-snk-personalized-filter-editor{display:flex;border-radius:var(--border--radius-regular)}.SnkFilterPersonalized_list-item--modal.sc-snk-personalized-filter-editor:hover{background-color:var(--background--medium, #f0f3f7)}.SnkFilterPersonalized_list-actions.sc-snk-personalized-filter-editor{display:none;align-items:center;gap:var(--space--3xs)}.SnkFilterPersonalized_list-item--modal.sc-snk-personalized-filter-editor:hover .SnkFilterPersonalized_list-actions.sc-snk-personalized-filter-editor{display:flex}.SnkFilterPersonalized_list-item--chip.sc-snk-personalized-filter-editor{display:flex;flex-direction:column;border:var(--border--small, 1px solid) var(--color-strokes, #DCE0E8);border-radius:var(--border--radius-regular)}.SnkFilterPersonalized_list-item--chip.sc-snk-personalized-filter-editor .sc-snk-personalized-filter-editor:first-of-type{gap:var(--space--3xs)}.SnkFilterPersonalized_list-icon.sc-snk-personalized-filter-editor{--ez-icon--color:var(--title--primary, #2B3A54);cursor:pointer}.SnkFilterPersonalized_list-icon.sc-snk-personalized-filter-editor:hover{outline:none;color:var(--color--primary-600, #007a5a);fill:var(--color--primary-600, #007a5a);--ez-icon--color:var(--color--primary-600, #007a5a)}";

const SnkFilterPersonalized = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.deleteFilter = createEvent(this, "deleteFilter", 7);
    this.editFilter = createEvent(this, "editFilter", 7);
    this.addFilter = createEvent(this, "addFilter", 7);
    this.valueChanged = createEvent(this, "valueChanged", 7);
    this.originalItems = [];
    this.messagesBuilder = undefined;
    this.presentationMode = EPresentationMode.MODAL;
    this.config = undefined;
    this.value = undefined;
    this.items = [];
  }
  /**
   * Apresenta o componente
   */
  async show() {
    const elem = document.querySelector("#param_0");
    if (elem)
      elem["setFocus"]();
  }
  configWatcher(newConfig) {
    this.items = this.originalItems = newConfig.groupedItems || [];
  }
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno modulo na estrutura da aplicação:
   * - Criar um arquivo no seguinte caminho: /messages/appmessages.msg.js.
   * Para conhecer os detalhes do módulo, vide o arquivo neste projeto "/src/lib/message/resources/snk-personalized-filter.msg.ts"
   */
  getMessage(key, params) {
    var _a;
    if (this.messagesBuilder)
      return this.messagesBuilder.getMessage(key, params);
    if ((_a = this._application) === null || _a === void 0 ? void 0 : _a.messagesBuilder)
      return this._application.messagesBuilder.getMessage(key, params);
  }
  getItemContent(item) {
    var _a, _b;
    const CheckboxElement = () => (h("ez-check", Object.assign({ class: "SnkFilterPersonalized_checkbox", id: `param_${item.id}`, key: item.id, value: item.visible, label: item.label, onEzChange: ({ detail: visible }) => this.handleItemChange.bind(this)(visible, item.id) }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${ElementIDUtils.getInternalIDInfo(`checkboxFilter_${item.id}`)}` })));
    const isVariable = !!((_b = (_a = item.props) === null || _a === void 0 ? void 0 : _a.personalizedFilter) === null || _b === void 0 ? void 0 : _b.parameters.length);
    return (h("div", { class: `${!this.isModalMode() ? "SnkFilterPersonalized_list-item--chip" : ""}` }, h("li", { class: `${this.isModalMode() ? "SnkFilterPersonalized_list-item--modal" : ""}` }, h("div", { class: "ez-flex ez-flex--align-items-center ez-flex--justify-between ez-size-width--full" }, h(CheckboxElement, null), this.buildModalListActions(item, isVariable))), (item.visible && isVariable) && (h("div", { class: "ez-row ez-padding--small" }, this.getFormField(item)))));
  }
  buildModalListActions(item, isVariable) {
    if (!this.isModalMode())
      return;
    return (this.isModalMode() ?
      h("div", { class: "SnkFilterPersonalized_list-actions" }, h("ez-icon", { class: 'SnkFilterPersonalized_list-icon', iconName: "edit", title: this.getMessage('snkPersonalizedFilter.listActions.edit'), onClick: () => this.editFilter.emit(item.id) }), h("ez-icon", { class: 'SnkFilterPersonalized_list-icon', iconName: "delete", title: this.getMessage('snkPersonalizedFilter.listActions.delete'), onClick: this.handleDeleteFilter.bind(this, item) }))
      :
        isVariable && (h("ez-badge", Object.assign({ class: "ez-badge--warning-subtle ez-margin-right--small", label: this.getMessage('snkPersonalizedFilter.info.badgeVariable'), size: "medium" }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${ElementIDUtils.getInternalIDInfo(`variableBadge_${item.id}`)}` }))));
  }
  isModalMode() {
    return this.presentationMode === EPresentationMode.MODAL;
  }
  doSearch(mode, argument, param) {
    const context = Object.assign({}, param.searchContext);
    context.searchOptions = Object.assign(Object.assign({}, context.searchOptions), { showInactives: "true" });
    return new Promise((resolve, reject) => {
      this._application.executePreparedSearch(mode, argument, context)
        .then(result => {
        resolve(result);
      }).catch(reason => {
        reject(reason);
      });
    });
  }
  getFormField(parentItem) {
    var _a, _b;
    const params = (_b = (_a = parentItem === null || parentItem === void 0 ? void 0 : parentItem.props) === null || _a === void 0 ? void 0 : _a.personalizedFilter) === null || _b === void 0 ? void 0 : _b.parameters;
    return params.map((param, index) => {
      var _a, _b, _c, _d;
      const formProp = Object.assign(Object.assign({}, param), { id: parentItem.id });
      const value = (_a = parentItem.value) === null || _a === void 0 ? void 0 : _a[index];
      const elemId = 'param_' + index;
      switch (param.userInterface) {
        case UserInterface.SEARCH:
          const isSearchPlus = ((_b = this.config.props) === null || _b === void 0 ? void 0 : _b["useSearchPlus"]) == true;
          const TagName = isSearchPlus ? "ez-search-plus" : "ez-search";
          return h(TagName, { id: elemId, suppressEmptyOption: true, value: value, onEzChange: evt => this.handleFilterItemChange(evt.detail, formProp), label: param.label, optionLoader: ({ mode, argument }) => this.doSearch(mode, argument, param) });
        case UserInterface.SWITCH:
        case UserInterface.CHECKBOX:
          const mode = UserInterface.SWITCH === param.userInterface ? CheckMode.SWITCH : CheckMode.REGULAR;
          return h("ez-check", { id: elemId, class: "ez-padding-bottom--medium", mode: mode, value: value, label: param.label, onEzChange: evt => this.handleFilterItemChange(evt.detail, formProp) });
        case UserInterface.DECIMALNUMBER:
          return h("ez-number-input", { id: elemId, label: param.label, value: value, precision: ((_c = param.props) === null || _c === void 0 ? void 0 : _c.precision) || 2, onEzChange: evt => this.handleFilterItemChange(evt.detail, formProp) });
        case UserInterface.INTEGERNUMBER:
          return h("ez-number-input", { id: elemId, label: param.label, value: value, precision: (_d = param.props) === null || _d === void 0 ? void 0 : _d.precision, onEzChange: evt => this.handleFilterItemChange(evt.detail, formProp) });
        case UserInterface.OPTIONSELECTOR:
          return h("ez-combo-box", { id: elemId, label: param.label, value: value, options: param.options, onEzChange: evt => this.handleFilterItemChange(evt.detail, formProp) });
        case UserInterface.DATE:
          return h("ez-date-input", { id: elemId, label: param.label, value: this.parseDate(value), onEzChange: evt => this.handleFilterItemChange(evt.detail, formProp) });
        case UserInterface.DATETIME:
          return h("ez-date-time-input", { id: elemId, label: param.label, value: this.parseDate(value), onEzChange: evt => this.handleFilterItemChange(evt.detail, formProp) });
        default:
          return h("ez-text-input", { id: elemId, label: param.label, value: value, onEzChange: evt => this.handleFilterItemChange(evt.detail, formProp) });
      }
    });
  }
  parseDate(objValue) {
    if (typeof objValue === "string") {
      let date = new Date(objValue);
      date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
      return date;
    }
    return objValue;
  }
  getVisibleCount(items) {
    return items.reduce((total, item) => {
      if (!!item.visible)
        return total + 1;
      return total;
    }, 0);
  }
  handleItemChange(visible, itemId) {
    this.items = this.originalItems = this.originalItems.map(item => {
      const isVisible = item.id === itemId ? visible : item.visible;
      return Object.assign(Object.assign({}, item), { visible: isVisible, active: isVisible });
    });
    this.emitChange();
  }
  handleSearchFilterList({ detail: query = "" }) {
    this.items = query ? this.originalItems.filter(item => item.label.toLowerCase().includes(query.toLowerCase())) : this.originalItems;
  }
  handleFilterItemChange(value, formProp) {
    var _a;
    const changedItem = this.items.find(({ id }) => id === formProp.id);
    const { parameters = [] } = ((_a = changedItem.props) === null || _a === void 0 ? void 0 : _a.personalizedFilter) || {};
    const indexToChangedParameter = parameters.findIndex(param => param.name === formProp.name);
    parameters[indexToChangedParameter] = formProp;
    changedItem.props.personalizedFilter.parameters = parameters;
    if (!changedItem.value) {
      changedItem.value = [];
    }
    changedItem.value[indexToChangedParameter] = value;
    const updatedItems = [
      ...this.items,
      changedItem
    ];
    this.items = Array.from(new Set(updatedItems));
    this.emitChange();
  }
  handleClearFilters() {
    this.emitChange(true);
  }
  emitChange(clear = false) {
    if (clear)
      this.items = this.originalItems;
    const items = this.items.map(item => (Object.assign(Object.assign({}, item), { visible: !clear && item.visible })));
    const value = this.getVisibleCount(items);
    this.valueChanged.emit({ value, items });
  }
  handleDeleteFilter(item) {
    this._application.confirm(this.getMessage('snkPersonalizedFilter.deleteConfirm.title'), this.getMessage('snkPersonalizedFilter.deleteConfirm.message', { filterName: item.label })).then((actionConfirmed) => {
      if (!actionConfirmed)
        return;
      this.deleteFilter.emit(item);
      this.items = this.originalItems = this.originalItems.filter(originalItem => originalItem.id !== item.id);
      this.emitChange();
    });
  }
  componentDidLoad() {
    if (this._element)
      ElementIDUtils.addIDInfoIfNotExists(this._element, 'filterContentEditor');
  }
  componentWillLoad() {
    var _a;
    this._application = ApplicationContext.getContextValue('__SNK__APPLICATION__');
    this.items = this.originalItems = ((_a = this.config) === null || _a === void 0 ? void 0 : _a.groupedItems) || [];
  }
  buildModeModalHeader() {
    if (this.presentationMode !== EPresentationMode.MODAL)
      return;
    return (h("div", { class: "ez-margin-bottom--medium" }, h(Fragment, null, h("ez-filter-input", Object.assign({ label: this.config.label, onEzChange: this.handleSearchFilterList.bind(this) }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${ElementIDUtils.getInternalIDInfo("filterSearch")}` })), h("span", { class: "ez-text ez-title--small ez-title--primary" }, " ", this.config.detailTitle, " "))));
  }
  buildModeModalFooter() {
    if (this.presentationMode !== EPresentationMode.MODAL)
      return;
    return (h("div", { class: "ez-flex ez-flex--justify-end grow ez-margin-top--medium ez-margin-bottom--small" }, h("ez-button", { class: "ez-button--tertiary ez-margin-right--small", size: "medium", label: this.getMessage('snkPersonalizedFilter.footerActions.clear'), onClick: this.handleClearFilters.bind(this) }), h("ez-button", { class: "ez-button--secondary ez-margin-right--small", size: "medium", label: this.getMessage('snkPersonalizedFilter.footerActions.create'), onClick: () => this.addFilter.emit() })));
  }
  buildContainerFiltersCreated() {
    if (this.items.length) {
      return (h("ez-scroller", { class: "SnkFilterPersonalized_list-scroller", direction: EzScrollDirection.VERTICAL }, h("ul", { class: `SnkFilterPersonalized_list-container ${!this.isModalMode() ? "SnkFilterPersonalized_list-container-chip" : ""}` }, this.items.map((itemConfig) => this.getItemContent(itemConfig)))));
    }
    else {
      return (h("div", { class: "ez-margin--auto" }, h("span", { class: "ez-text ez-text--secondary ez-text--small" }, this.getMessage('snkPersonalizedFilter.info.noDataFound'))));
    }
  }
  render() {
    if (!this.config || this.config.type !== FilterItemType.PERSONALIZED)
      return undefined;
    return (h(Host, null, this.buildModeModalHeader(), this.buildContainerFiltersCreated(), this.buildModeModalFooter()));
  }
  get _element() { return this; }
  static get watchers() { return {
    "config": ["configWatcher"]
  }; }
  static get style() { return snkPersonalizedFilterEditorCss; }
}, [2, "snk-personalized-filter-editor", {
    "messagesBuilder": [1040],
    "presentationMode": [2, "presentation-mode"],
    "config": [16],
    "value": [1040],
    "items": [32],
    "show": [64]
  }]);
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-personalized-filter-editor"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-personalized-filter-editor":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkFilterPersonalized);
      }
      break;
  } });
}

const SnkPersonalizedFilterEditor = SnkFilterPersonalized;
const defineCustomElement = defineCustomElement$1;

export { SnkPersonalizedFilterEditor, defineCustomElement };
