import { h, r as registerInstance, e as createEvent, g as getElement } from './index-e9c7ceaa.js';
import { S as SelectedItemType } from './index-620ac460.js';
import { UserInterface, JSUtils, ElementIDUtils, ApplicationContext, StringUtils, DataType } from '@sankhyalabs/core';
import { ModalAction } from '@sankhyalabs/ezui/dist/collection/components/ez-modal-container';
import { b as FilterConfigType, c as FilterEntities, d as FilterUserConfigTypes } from './index-8acbae97.js';
import { P as PersonalizedFilterUtils } from './PersonalizedFilterUtils-d2439a9a.js';
import './filter-item-type.enum-d45e026f.js';

const ICON_MODES = {
  [UserInterface.SHORTTEXT]: 'text',
  [UserInterface.LONGTEXT]: 'text',
  [UserInterface.INTEGERNUMBER]: 'number',
  [UserInterface.DECIMALNUMBER]: 'number',
  [UserInterface.DATE]: 'calendar',
  [UserInterface.DATETIME]: 'calendar',
  [UserInterface.SWITCH]: 'boolean',
  [UserInterface.CHECKBOX]: 'check-circle-inverted',
  [UserInterface.OPTIONSELECTOR]: 'list',
  [UserInterface.SEARCH]: 'search',
  [UserInterface.HTML]: 'tag_code',
  [UserInterface.IMAGE]: 'png',
  [UserInterface.FILE]: 'edit-file',
  [UserInterface.TIME]: 'timer-outline',
  [UserInterface.ELAPSEDTIME]: 'timer',
  [UserInterface.MASKEDTEXT]: 'text',
  [UserInterface.PASSWORD]: 'email',
};
const ListItem = ({ userInterface, description }) => {
  return (h("ez-icon", { iconName: ICON_MODES[userInterface], class: "ez-padding-left--small", title: description }));
};

const snkFilterFieldSearchCss = ".sc-snk-filter-field-search-h{--snk-filter-field-search--container-width:468px;--snk-filter-field-search--container-height:322px}.snk-filter-field-search__container.sc-snk-filter-field-search{display:flex;flex-direction:column;padding:var(--space--medium);width:var(--snk-filter-field-search--container-width);height:var(--snk-filter-field-search--container-height)}.snk-filter-field-search__section.sc-snk-filter-field-search{display:grid;grid-template-columns:1fr 1fr;place-items:flex-start;overflow:hidden;gap:var(--space--small)}.snk-filter-field-search__input.sc-snk-filter-field-search{margin-bottom:var(--space--medium)}.snk-filter-field-search__list_container.sc-snk-filter-field-search{display:flex;flex-direction:column}.snk-filter-field-search__list.sc-snk-filter-field-search{overflow-y:auto}";

const SNK_CONTEXT_KEY = "__SNK__APPLICATION__";
const ENTITY_NAME_PATTERN = /\w+:\/\/(\w+)/;
const SnkFilterFieldSearch = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezSelectFilterItem = createEvent(this, "ezSelectFilterItem", 7);
    this._currentMetadata = null;
    this._filterText = "";
    this._isLoading = false;
    this.searchable = true;
    this.fieldsDataSource = undefined;
    this.breadcrumbItems = [];
    this.linkItems = [];
    this.fieldItems = [];
    this.searchEmpty = false;
    this.groupEmpty = false;
  }
  /**
   * /**
   * Realiza a abertura do componente abaixo do elemento HTML informado
   * e faz a primeira carga de dados.
   *
   * @param {HTMLElement} element - Elemento HTML onde o snk-filter-field-search irá se posicionar abaixo.
   * @param {IEzPopoverAnchorOptions} options - opções para regular o posicionamento do componente.
   */
  async show(element, options) {
    var _a;
    if (element) {
      (_a = this._ezPopover) === null || _a === void 0 ? void 0 : _a.showUnder(element, options);
    }
    else {
      this._ezPopover.show();
    }
    return this.loadData();
  }
  /**
   * Filtra a fonte de dados do componente.
   * @param {string} filterText - Texto para filtrar a fonte de dados.
   * @throws {Error} - Quando o componente estiver com a propriedade searchable como true.
  */
  async applyFilter(filterText) {
    if (this.searchable)
      throw new Error('This method is not available when searchable is true');
    this.handleFilterChange(filterText);
  }
  async loadData() {
    var _a, _b;
    this._isLoading = true;
    let metadata = await this.fieldsDataSource.fetchData(this._currentLink);
    this._currentLink = metadata.currentLink;
    const { fields, links } = metadata || {};
    if (!Array.isArray(fields) || !Array.isArray(links))
      throw new Error('Invalid metadata');
    this._currentMetadata = metadata;
    this.mapDataSourceToLinkItems();
    this.mapDataSourceToFieldItems();
    this._isLoading = false;
    (_a = this._ezFieldList) === null || _a === void 0 ? void 0 : _a.scrollToTop();
    (_b = this._ezLinkList) === null || _b === void 0 ? void 0 : _b.scrollToTop();
  }
  mapDataSourceToLinkItems() {
    var _a;
    const { links } = this._currentMetadata;
    const filterLinkLabelMessage = this.getMessage('snkFilterFieldSearch.linkLabel', { link: (_a = this._currentLink) === null || _a === void 0 ? void 0 : _a.description });
    const items = links.map(link => (Object.assign({ label: link.description }, link)));
    this.groupEmpty = Boolean(items.length === 0);
    this.linkItems = [{
        group: filterLinkLabelMessage,
        items,
      }];
    if (this.breadcrumbItems.length === 0) {
      this.breadcrumbItems = [Object.assign({ id: JSUtils.generateUUID(), label: this._currentLink.description }, this._currentLink)];
    }
  }
  mapDataSourceToFieldItems() {
    var _a;
    const fields = this._currentMetadata.fields;
    const filterFieldLabelMessage = this.getMessage('snkFilterFieldSearch.fieldLabel', { link: (_a = this._currentLink) === null || _a === void 0 ? void 0 : _a.description });
    const filteredFields = fields.filter(field => {
      if (!this._currentLink)
        return true;
      const searchableByDescription = field.description.toLowerCase().includes(this._filterText.toLowerCase());
      const searchableByName = field.name.toLowerCase().includes(this._filterText.toLowerCase());
      return searchableByDescription || searchableByName;
    });
    const items = filteredFields.map(field => (Object.assign({ label: field.description }, field)));
    this.searchEmpty = Boolean(this._filterText && items.length === 0);
    this.fieldItems = [{
        group: filterFieldLabelMessage,
        items
      }];
  }
  handleFilterChange(filterText) {
    if (this._isLoading)
      return;
    this._filterText = filterText;
    this.mapDataSourceToFieldItems();
  }
  handleSelectLink({ detail: item }) {
    if (this._isLoading)
      return;
    const breadcrumbByIndex = this.breadcrumbItems.findIndex(breadcrumbItem => breadcrumbItem.id === item.id);
    if (breadcrumbByIndex > -1) {
      this.breadcrumbItems = this.breadcrumbItems.slice(0, (breadcrumbByIndex + 1));
    }
    else {
      this.breadcrumbItems = [...this.breadcrumbItems, Object.assign({ id: JSUtils.generateUUID(), label: item.description }, item)];
    }
    const selectedItem = Object.assign(Object.assign({}, item), { type: SelectedItemType.LINK });
    this._currentLink = selectedItem;
    this.ezSelectFilterItem.emit(selectedItem);
    this.loadData();
  }
  getEntityFromBreadCrumbItem(item) {
    const result = ENTITY_NAME_PATTERN.exec(item.uri);
    if (!result) {
      return undefined;
    }
    return result[1];
  }
  handleSelectField({ detail: item }) {
    var _a;
    const breadcrumbPath = this.breadcrumbItems.map(breadcrumbItem => breadcrumbItem.label).join('>>');
    const selectedField = Object.assign(Object.assign({}, item), { type: SelectedItemType.FIELD, entityPath: this.breadcrumbItems.map(item => this.getEntityFromBreadCrumbItem(item)).filter(item => item != undefined), path: `${breadcrumbPath} >> ${item.description}` });
    this.ezSelectFilterItem.emit(selectedField);
    (_a = this._ezPopover) === null || _a === void 0 ? void 0 : _a.hide();
  }
  getElementID(sufix) {
    return {
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(sufix)
    };
  }
  /**
   * 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-filter-field-search.msg.ts"
  */
  getMessage(key, params) {
    var _a, _b, _c;
    if (!this._application)
      this._application = ApplicationContext.getContextValue(SNK_CONTEXT_KEY);
    return (_c = (_b = (_a = this._application) === null || _a === void 0 ? void 0 : _a.messagesBuilder) === null || _b === void 0 ? void 0 : _b.getMessage) === null || _c === void 0 ? void 0 : _c.call(_b, key, params);
  }
  ;
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue(SNK_CONTEXT_KEY);
  }
  componentDidLoad() {
    ElementIDUtils.addIDInfoIfNotExists(this._ezPopover, 'popover');
  }
  disconnectedCallback() {
    var _a;
    (_a = this._ezPopover) === null || _a === void 0 ? void 0 : _a.hide();
  }
  render() {
    var _a;
    const searchLabelMessage = this.getMessage('snkFilterFieldSearch.searchLabel');
    return (h("ez-popover", Object.assign({ ref: (el) => this._ezPopover = el, role: "dialog", overlayType: "none", "aria-hidden": !((_a = this._ezPopover) === null || _a === void 0 ? void 0 : _a.opened) }, this.getElementID('EzPopover')), h("div", { class: "snk-filter-field-search__container" }, h("header", { class: "snk-filter-field-search__header" }, this.searchable && !!searchLabelMessage && (h("ez-filter-input", Object.assign({ class: "snk-filter-field-search__input", label: searchLabelMessage, asyncSearch: true, canShowError: false, onEzSearching: (event) => this.handleFilterChange.bind(this)(event.detail), "aria-label": searchLabelMessage, "aria-required": "false", "aria-invalid": "false" }, this.getElementID('EzFilterInput')))), this.breadcrumbItems.length > 0 && (h("ez-breadcrumb", Object.assign({ items: this.breadcrumbItems, onSelectedItem: this.handleSelectLink.bind(this), role: "navigation", "aria-current": "step" }, this.getElementID('EzBreadcrumb')))), h("hr", { class: "ez-divider-horizontal ez-margin-vertical--medium" })), h("section", { class: `snk-filter-field-search__section ${(this.groupEmpty && this.searchEmpty) && " ez-margin--auto"}` }, this.groupEmpty ?
      h("div", { class: "ez-margin--auto" }, h("span", { class: "ez-text ez-text--secondary ez-text--medium" }, this.getMessage('snkFilterFieldSearch.groupEmpty')))
      :
        h("ez-list", Object.assign({ ref: (el) => this._ezLinkList = el, class: "snk-filter-field-search__list", id: "filterLinkList", useGroups: true, dataSource: this.linkItems, onEzSelectItem: this.handleSelectLink.bind(this), hoverFeedback: true, ezSelectable: true, itemSlotBuilder: listItem => h("ez-badge", { label: listItem.fieldCount }), "aria-describedby": "filterLinkLabel" }, this.getElementID('EzListLinks'))), this.searchEmpty ?
      h("div", { class: "ez-margin--auto" }, h("span", { class: "ez-text ez-text--secondary ez-text--medium" }, this.getMessage('snkFilterFieldSearch.searchEmpty')))
      :
        h("ez-list", Object.assign({ ref: (el) => this._ezFieldList = el, class: "snk-filter-field-search__list", id: "filterFieldList", useGroups: true, dataSource: this.fieldItems, onEzSelectItem: this.handleSelectField.bind(this), hoverFeedback: true, ezSelectable: true, itemSlotBuilder: ListItem, "aria-describedby": "filterFieldLabel" }, this.getElementID('EzListFields')))))));
  }
};
SnkFilterFieldSearch.style = snkFilterFieldSearchCss;

const snkFilterParamConfigCss = ":host{--snk-filter-param-config__expression--color:var(--title--primary, #2b3a54);display:flex;position:relative}.snk-filter-param-config__expression{--text-area__input--disabled--color:var(--snk-filter-param-config__expression--color)}";

const SnkFilterParamConfig = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this._opened = false;
    this._configType = FilterConfigType.SYSTEM_CONFIG;
    this._expressionItem = undefined;
    this._informedInstance = false;
    this._canSave = false;
    this.messagesBuilder = undefined;
  }
  /**
   * Abre o modal de configuração de valor variável
   */
  open(expressionItem) {
    this._opened = true;
    this._expressionItem = expressionItem;
    this.loadValues();
    return new Promise(accept => {
      this._promiseResolver = accept;
    });
  }
  /**
   * Fecha o modal de configuração de valor variável
   */
  close() {
    this._opened = false;
    return new Promise(accept => {
      this._promiseResolver = accept;
    });
  }
  /**
   * 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-filter-param-config.msg.ts"
   */
  getMessage(key, params) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
  }
  getConfigValue(configName, inputName, inputAlias = "") {
    var _a, _b, _c;
    return ((_b = (_a = this._expressionItem) === null || _a === void 0 ? void 0 : _a[configName]) === null || _b === void 0 ? void 0 : _b[inputName])
      || ((_c = this._expressionItem) === null || _c === void 0 ? void 0 : _c[inputAlias || inputName]);
  }
  loadValues() {
    var _a;
    const entityName = this.getConfigValue("systemConfig", "entity", "entityName");
    const fieldName = this.getConfigValue("systemConfig", "fieldName");
    const description = this.getConfigValue("userConfig", "description");
    const type = this.getConfigValue("userConfig", "type");
    if (((_a = this._expressionItem) === null || _a === void 0 ? void 0 : _a.userConfig) != undefined) {
      this._configType = FilterConfigType.USER_CONFIG;
    }
    else {
      this._configType = FilterConfigType.SYSTEM_CONFIG;
    }
    if (!StringUtils.isEmpty(entityName) && !StringUtils.isEmpty(fieldName)) {
      this._instanceElement.value = { value: entityName, label: "" };
      this._fieldElement.value = { value: fieldName, label: "" };
    }
    if (!StringUtils.isEmpty(description) && !StringUtils.isEmpty(type)) {
      this._descriptionElement.value = description;
      this._typeElement.value = type;
    }
    this.buildFilterExpression();
  }
  changeDefinitionUsed(option) {
    this._configType = option !== null && option !== void 0 ? option : FilterConfigType.SYSTEM_CONFIG;
    if (this._configType === FilterConfigType.SYSTEM_CONFIG) {
      const entityName = this.getConfigValue("systemConfig", "entity", "entityName");
      const fieldName = this.getConfigValue("systemConfig", "fieldName");
      this._instanceElement.value = this._instanceElement.value || { value: entityName, label: "" };
      this._fieldElement.value = this._fieldElement.value || { value: fieldName, label: "" };
    }
    else if (this._configType === FilterConfigType.USER_CONFIG) {
      const description = this.getConfigValue("userConfig", "description");
      const type = this.getConfigValue("userConfig", "type");
      this._descriptionElement.value = this._descriptionElement.value || description;
      this._typeElement.value = this._typeElement.value || type;
    }
    this.buildFilterExpression();
  }
  getTypeValue() {
    var _a;
    const value = (_a = this._typeElement) === null || _a === void 0 ? void 0 : _a.value;
    return ((value === null || value === void 0 ? void 0 : value.value) || value);
  }
  getExpressionValues() {
    var _a, _b, _c, _d, _e;
    let systemConfig;
    let userConfig;
    if (this._configType === FilterConfigType.SYSTEM_CONFIG) {
      const entity = (_b = (_a = this._instanceElement) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.value;
      const fieldName = (_d = (_c = this._fieldElement) === null || _c === void 0 ? void 0 : _c.value) === null || _d === void 0 ? void 0 : _d.value;
      systemConfig = { entity, fieldName };
    }
    else if (this._configType === FilterConfigType.USER_CONFIG) {
      const description = (_e = this._descriptionElement) === null || _e === void 0 ? void 0 : _e.value;
      const type = this.getTypeValue();
      userConfig = { description, type };
    }
    return Object.assign(Object.assign(Object.assign({}, this._expressionItem), { systemConfig }), { userConfig });
  }
  isEnabled(value) {
    return this._configType === value;
  }
  isInformedInstance() {
    var _a, _b;
    return !StringUtils.isEmpty((_b = (_a = this._instanceElement) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.value);
  }
  save() {
    var _a;
    this._expressionItem = Object.assign(Object.assign({}, this.getExpressionValues()), { expression: (_a = this._expressionElement) === null || _a === void 0 ? void 0 : _a.value });
    this._promiseResolver(this._expressionItem);
    this._opened = false;
  }
  buildFilterExpression() {
    var _a;
    this._informedInstance = this.isInformedInstance();
    const expression = PersonalizedFilterUtils.buildFilterExpression(this.getExpressionValues());
    this._expressionElement.value = expression || ((_a = this._expressionItem) === null || _a === void 0 ? void 0 : _a.expression);
    this._canSave = this.getCanSave();
  }
  handleChangeInstance() {
    this._informedInstance = this.isInformedInstance();
    if (this._fieldElement != undefined && !StringUtils.isEmpty(this._fieldElement.value)) {
      this._fieldElement.value = null;
    }
    this.buildFilterExpression();
  }
  getInstanceCriteria() {
    var _a, _b;
    const value = (_b = (_a = this._instanceElement) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.value;
    return {
      expression: "this.NOMETAB = (SELECT NOMETAB FROM TDDINS WHERE NOMEINSTANCIA = ?)",
      params: [
        {
          name: "NOMEINSTANCIA",
          dataType: DataType.TEXT,
          value
        }
      ]
    };
  }
  onSearch({ mode, argument }, entity) {
    if (this._application == undefined || !this._opened) {
      return;
    }
    const isField = entity === FilterEntities.FIELD;
    const criteria = isField ? this.getInstanceCriteria() : undefined;
    const messageKey = `snkFilterParamConfig.label${isField ? "Field" : "Instance"}`;
    const entityDescription = this.getMessage(messageKey);
    const searchOptions = {
      descriptionFieldName: isField ? "DESCRCAMPO" : "DESCRINSTANCIA",
      codeFieldName: isField ? "NOMECAMPO" : "NOMEINSTANCIA",
      showInactives: false
    };
    const options = {
      entity,
      entityDescription,
      criteria,
      searchOptions
    };
    return new Promise((resolve) => {
      this._application.executePreparedSearch(mode, argument, options).then(res => resolve(res));
    });
  }
  getElementID(sufix) {
    return {
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(sufix)
    };
  }
  getCanSave() {
    var _a;
    if (this._configType === FilterConfigType.USER_CONFIG) {
      const description = (_a = this._descriptionElement) === null || _a === void 0 ? void 0 : _a.value;
      const type = this.getTypeValue();
      return !StringUtils.isEmpty(description) && !StringUtils.isEmpty(type);
    }
    return true;
  }
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  render() {
    ElementIDUtils.addIDInfoIfNotExists(this._element, 'snkFilterParamConfig');
    return (h("ez-popup", Object.assign({ useHeader: false, size: "small", heightMode: "auto", opened: this._opened }, this.getElementID("popup")), h("ez-modal-container", Object.assign({ onEzModalAction: (evt) => {
        if (evt.detail === ModalAction.CLOSE)
          this.close();
      }, modalTitle: this.getMessage("snkFilterParamConfig.modalTitle") }, this.getElementID("modalContainer")), h("div", { class: "ez-flex" }, h("div", { class: "ez-col ez-col--sd-6 ez-flex--column" }, h("ez-radio-button", Object.assign({ value: this._configType, onEzChange: (evt) => this.changeDefinitionUsed(evt.detail) }, this.getElementID("systemConfigOption")), h("ez-radio-button-option", { label: this.getMessage("snkFilterParamConfig.labelSystemConfig"), value: FilterConfigType.SYSTEM_CONFIG })), h("ez-search", Object.assign({ ref: (ref) => this._instanceElement = ref, label: this.getMessage("snkFilterParamConfig.labelInstance"), enabled: this.isEnabled(FilterConfigType.SYSTEM_CONFIG), suppressEmptyOption: true, showOptionValue: false, showSelectedValue: false, onEzChange: () => this.handleChangeInstance(), optionLoader: (searchArgument) => this.onSearch(searchArgument, FilterEntities.INSTANCE) }, this.getElementID("configFindEntity"))), h("ez-search", Object.assign({ ref: (ref) => this._fieldElement = ref, label: this.getMessage("snkFilterParamConfig.labelField"), enabled: this.isEnabled(FilterConfigType.SYSTEM_CONFIG) && this._informedInstance, suppressEmptyOption: true, showOptionValue: false, showSelectedValue: false, onEzChange: () => this.buildFilterExpression(), optionLoader: (searchArgument) => this.onSearch(searchArgument, FilterEntities.FIELD) }, this.getElementID("configFindField")))), h("div", { class: "ez-flex ez-padding--medium" }, h("hr", { class: "ez-divider-vertical" })), h("div", { class: "ez-col ez-col--sd-6 ez-flex--column" }, h("ez-radio-button", Object.assign({ value: this._configType, onEzChange: (evt) => this.changeDefinitionUsed(evt.detail) }, this.getElementID("userConfigOption")), h("ez-radio-button-option", { label: this.getMessage("snkFilterParamConfig.labelUserConfig"), value: FilterConfigType.USER_CONFIG })), h("ez-text-input", Object.assign({ ref: (ref) => this._descriptionElement = ref, label: this.getMessage("snkFilterParamConfig.labelDescription"), enabled: this.isEnabled(FilterConfigType.USER_CONFIG), onEzChange: () => this.buildFilterExpression() }, this.getElementID("configParamLabel"))), h("ez-combo-box", Object.assign({ ref: (ref) => this._typeElement = ref, label: this.getMessage("snkFilterParamConfig.labelType"), enabled: this.isEnabled(FilterConfigType.USER_CONFIG), suppressEmptyOption: true, onEzChange: () => this.buildFilterExpression() }, this.getElementID("configParamType")), Object.keys(FilterUserConfigTypes).map((configType) => {
      return (h("option", { value: FilterUserConfigTypes[configType] }, this.getMessage(`snkFilterParamConfig.labelTypeValues.${configType.toLowerCase()}`)));
    })))), h("ez-text-area", Object.assign({ ref: (ref) => this._expressionElement = ref, class: "snk-filter-param-config__expression", label: this.getMessage("snkFilterParamConfig.labelExpression"), enabled: false }, this.getElementID("presentationExpression"))), h("div", { class: "ez-col ez-col--sd-12 ez-flex--justify-end ez-margin-vertical--small" }, h("ez-button", Object.assign({ class: "ez-padding-right--medium", label: this.getMessage("snkFilterParamConfig.labelCancel"), onClick: () => this.close() }, this.getElementID("cancelEditParam"))), h("ez-button", Object.assign({ class: "ez-button--primary", label: this.getMessage("snkFilterParamConfig.labelSave"), onClick: () => this.save(), enabled: this._canSave }, this.getElementID("saveEditParam")))))));
  }
  get _element() { return getElement(this); }
};
SnkFilterParamConfig.style = snkFilterParamConfigCss;

export { SnkFilterFieldSearch as snk_filter_field_search, SnkFilterParamConfig as snk_filter_param_config };
