import { proxyCustomElement, HTMLElement, h } from '@stencil/core/internal/client';
import { StringUtils, DataType, ElementIDUtils, ApplicationContext } from '@sankhyalabs/core';
import { ModalAction } from '@sankhyalabs/ezui/dist/collection/components/ez-modal-container';
import { b as FilterConfigType, P as PersonalizedFilterUtils, c as FilterEntities, d as FilterUserConfigTypes } from './PersonalizedFilterUtils.js';

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 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    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 this; }
  static get style() { return snkFilterParamConfigCss; }
}, [0, "snk-filter-param-config", {
    "messagesBuilder": [1040],
    "_opened": [32],
    "_configType": [32],
    "_expressionItem": [32],
    "_informedInstance": [32],
    "_canSave": [32],
    "open": [64],
    "close": [64]
  }]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-filter-param-config"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-filter-param-config":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkFilterParamConfig);
      }
      break;
  } });
}

export { SnkFilterParamConfig as S, defineCustomElement as d };
