'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-a7b0c73d.js');
const core = require('@sankhyalabs/core');
require('./ApplicationUtils-5cc05979.js');
const CSSVarsUtils = require('./CSSVarsUtils-f20973d1.js');
require('./DialogType-2114c337.js');
require('./CheckMode-ecb90b87.js');
const index$1 = require('./index-1be40f19.js');
const FormLayout = require('./FormLayout-18853e70.js');

const ezSearchPlusCss = ":host{--ez-search--height:42px;--ez-search--width:100%;--ez-search__icon--width:48px;--ez-search--border-radius:var(--border--radius-medium, 12px);--ez-search--border-radius-small:var(--border--radius-small, 6px);--ez-search--font-size:var(--text--medium, 14px);--ez-search--font-family:var(--font-pattern, Arial);--ez-search--font-weight--large:var(--text-weight--large, 500);--ez-search--font-weight--medium:var(--text-weight--medium, 400);--ez-search--background-color--xlight:var(--background--xlight, #fff);--ez-search--background-medium:var(--background--medium, #f0f3f7);--ez-search--line-height:calc(var(--text--medium, 14px) + 4px);--ez-search__input--background-color:var(--background--medium, #e0e0e0);--ez-search__input--border:var(--border--medium, 2px solid);--ez-search__input--border-color:var(--ez-search__input--background-color);--ez-search__input--focus--border-color:var(--color--primary, #008561);--ez-search__input--disabled--background-color:var(--color--disable-secondary, #F2F5F8);--ez-search__input--disabled--color:var(--text--disable, #AFB6C0);--ez-search__input--error--border-color:#CC2936;--ez-search__btn--color:var(--title--primary, #2B3A54);--ez-search__btn-disabled--color:var(--text--disable, #AFB6C0);--ez-search__btn-hover--color:var(--color--primary, #4e4e4e);--ez-search__label--color:var(--title--primary, #2B3A54);--ez-search__list-title--primary:var(--title--primary, #2B3A54);--ez-search__list-text--primary:var(--text--primary, #626e82);--ez-search__list-height:calc(var(--ez-search--font-size) + var(--ez-search--space--medium) + 4px);--ez-search__list-min-width:64px;--ez-search--space--medium:var(--space--medium, 12px);--ez-search--space--small:var(--space--small, 6px);--ez-search__scrollbar--color-default:var(--scrollbar--default, #626e82);--ez-search__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--ez-search__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--ez-search__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--ez-search__scrollbar--border-radius:var(--border--radius-small, 6px);--ez-search__scrollbar--width:var(--space--medium, 12px);display:flex;flex-wrap:wrap;position:relative;width:var(--ez-search--width)}ez-icon{--ez-icon--color:inherit;font-weight:var(--text-weight--large, 600)}.suppressed-search-input{--ez-text-input__input--border-color:var(--color--strokes, #dce0e8);--ez-text-input__input--disabled--background-color:var(--background--xlight, #fff);--ez-text-input__input--disabled--color:var(--title--primary, #2B3A54)}.list-container{min-width:var(--ez-search__list-min-width);overflow:auto;position:relative;width:100%}.list-wrapper{display:flex;flex-direction:column;box-sizing:border-box;width:0;z-index:var(--more-visible, 2);max-height:350px;min-width:150px;background-color:var(--ez-search--background-color--xlight);border-radius:var(--ez-search--border-radius);box-shadow:var(--shadow, 0px 0px 16px 0px #000)}.list-options{margin-top:0px;box-sizing:border-box;width:100%;height:100%;padding:0;display:flex;flex-direction:column;scroll-behavior:smooth;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;scrollbar-color:var(--ez-search__scrollbar--color-clicked) var(--ez-search__scrollbar--color-background)}.list-options::-webkit-scrollbar{background-color:var(--scrollbar--background);width:var(--space--small);max-width:var(--space--small);min-width:var(--space--small);height:var(--space--small);max-height:var(--space--small);min-height:var(--space--small)}.list-options::-webkit-scrollbar-track{background-color:var(--ez-search__scrollbar--color-background);border-radius:var(--ez-search__scrollbar--border-radius)}.list-options::-webkit-scrollbar-thumb{background-color:var(--ez-search__scrollbar--color-default);border-radius:var(--ez-search__scrollbar--border-radius)}.list-options::-webkit-scrollbar-thumb:vertical:hover,.list-options::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--ez-search__scrollbar--color-hover)}.list-options::-webkit-scrollbar-thumb:vertical:active,.list-options::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--ez-search__scrollbar--color-clicked)}.item{display:flex;align-items:center;width:100%;box-sizing:border-box;list-style-type:none;cursor:pointer;border-radius:var(--ez-search--border-radius-small);gap:var(--space--small, 6px)}.item__value,.item__label{flex-basis:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--ez-search__list-title--primary);font-family:var(--ez-search--font-family);font-size:var(--ez-search--font-size);line-height:var(--ez-search--line-height)}.item__label{font-weight:var(--ez-search--font-weight--medium)}.item__label--bold{font-weight:var(--ez-search--font-weight--large)}.item__value{text-align:center;color:var(--ez-search__list-text--primary);font-weight:var(--ez-search--font-weight--large)}.item__value--hidden{visibility:hidden;position:absolute;white-space:nowrap;z-index:-1;top:0;left:0}.item__label{text-align:left}.message{text-align:center;display:flex;justify-content:center;align-items:center;list-style-type:none;min-height:var(--ez-search__list-height)}.message__no-result{color:var(--ez-search__list-title--primary);font-family:var(--ez-search--font-family);font-size:var(--ez-search--font-size)}.message__loading{border-radius:50%;width:14px;height:14px;-webkit-animation:spin 1s linear infinite;animation:spin 1s linear infinite;border:3px solid var(--ez-search__list-title--primary);border-top:3px solid transparent}.item__list>li:hover{background-color:var(--ez-search--background-medium)}.preselected{background-color:var(--background--medium)}.btn{outline:none;border:none;background:none;cursor:pointer;color:var(--ez-search__btn--color)}.btn:disabled{cursor:not-allowed;color:var(--ez-search__btn-disabled--color)}.btn:disabled:hover{cursor:not-allowed;color:var(--ez-search__btn-disabled--color)}.btn:hover{color:var(--ez-search__btn-hover--color)}.btn__close{visibility:hidden}ez-text-input:hover .btn__close,ez-text-input:focus .btn__close{visibility:visible}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@supports not (scrollbar-width: thin){.item{padding-right:8px}}.ez-search-plus__container{display:flex;flex-grow:1;gap:3px}.ez-search-plus__text-input{--ez-text-input--border-top-left-radius:0px;--ez-text-input--border-bottom-left-radius:0px;outline:none}.ez-search-plus__code-input-no-border{--ez-text-input--border-top-right-radius:0px;--ez-text-input--border-bottom-right-radius:0px}.ez-search-plus__code-input{max-width:85px}.ez-search-plus__code-input-full{width:100%}.description-input-container{width:100%;outline:none}";

const EzSearchPlus = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.ezChange = index.createEvent(this, "ezChange", 7);
    this.SEARCH_DESCRIPTION_TIMEOUT = 300;
    this.INTERVAL_TO_RETRY_ASYNC_VALUE = 100;
    this.value = undefined;
    this.enabled = true;
    this.disableCodeInput = false;
    this.disableDescriptionInput = false;
    this.label = undefined;
    this.codLabel = undefined;
    this.hideDescriptionInput = false;
    this.canShowError = true;
    this.errorMessage = undefined;
    this.mode = "regular";
    this.contextProperties = undefined;
    this.optionLoader = undefined;
    this.showOptionValue = true;
    this.stopPropagateEnterKeyEvent = false;
    this.autoFocus = false;
    this.showSelectedValue = true;
    this.suppressEmptyOption = false;
    this.hideErrorOnFocusOut = true;
    this.listOptionsPosition = undefined;
    this.isTextSearch = false;
    this.ignoreLimitCharsToSearch = false;
    this.suppressSearch = false;
    this.suppressPreLoad = true;
    this.ensureClearButtonVisible = false;
    this.descriptionValue = "";
    this.codeValue = "";
    this.isLoadingDescription = false;
    this.searchDescriptionIsOpen = false;
    this.visibleOptions = undefined;
    this.showLoading = true;
  }
  async observeValue(newValue, oldValue) {
    const newNormalizedValue = this.normalizeValueToCodeValue(newValue);
    const oldNormalizedValue = this.normalizeValueToCodeValue(oldValue);
    if (newNormalizedValue === oldNormalizedValue) {
      return;
    }
    if (newNormalizedValue === undefined) {
      this.codeValue = undefined;
      this.descriptionValue = undefined;
      this.ezChange.emit(undefined);
      return;
    }
    this.codeValue = newNormalizedValue;
    try {
      this.descriptionValue = await this.normalizeCodeToDescriptionValue(newValue);
      if (this.descriptionValue === null || this.descriptionValue === undefined) {
        throw new Error("Valor não encontrado!");
      }
    }
    catch (err) {
      this.value = undefined;
      console.warn("[EzSearchPlus] Erro ao obter descrição do registro.", err);
      throw err;
    }
    this.value = this.buildCurrentValue();
    this.ezChange.emit(this.value);
  }
  canShowLoadSpinDescription() {
    return this.isLoadingDescription;
  }
  /**
   * Aplica o foco no campo.
   */
  async setFocus(options) {
    var _a;
    if (this.disableCodeInput) {
      (_a = this._textInputDescriptionValue) === null || _a === void 0 ? void 0 : _a.setFocus(options);
      return;
    }
    if (this._latestFocusedInputElement) {
      this._latestFocusedInputElement.setFocus(options);
      return;
    }
    this._textInputCodeValue.setFocus(options);
  }
  /**
  * Obtém o valor do componente só após a compo de apresentação
  * ter sido resolvido pelo option loader quando necessário
  */
  async getValueAsync() {
    if (!this.isLoadingDescription) {
      const currentOpt = this.buildCurrentValue();
      return new Promise(resolve => resolve(currentOpt));
    }
    return new Promise(resolve => {
      let id = setInterval(() => {
        if (!this.isLoadingDescription) {
          clearInterval(id);
          const currentOpt = this.buildCurrentValue();
          resolve(currentOpt);
        }
      }, this.INTERVAL_TO_RETRY_ASYNC_VALUE);
    });
  }
  /**
  * Limpa o valor do campo de pesquisa
  */
  async clearValue() {
    this.clearSearch();
  }
  /**
  * Remove o foco do campo.
  */
  async setBlur() {
    var _a, _b;
    (_a = this._textInputCodeValue) === null || _a === void 0 ? void 0 : _a.setBlur();
    (_b = this._textInputDescriptionValue) === null || _b === void 0 ? void 0 : _b.setBlur();
  }
  /**
  * Retorna se o conteúdo é inválido.
  */
  async isInvalid() {
    return typeof this.errorMessage === "string" && this.errorMessage.trim() !== "";
  }
  async componentWillLoad() {
    this.i18n = await index$1.initI18n();
    if (this.value && core.StringUtils.isEmpty(this.codeValue)) {
      await this.observeValue(this.value, undefined);
    }
  }
  componentDidLoad() {
    CSSVarsUtils.CSSVarsUtils.applyVarsTextInput(this.el, this._textInputCodeValue);
    CSSVarsUtils.CSSVarsUtils.applyVarsTextInput(this.el, this._textInputDescriptionValue);
  }
  connectedCallback() {
    this.initKeyboardManager();
    if (this.autoFocus) {
      requestAnimationFrame(() => {
        this.setFocus({ selectText: true });
      });
    }
  }
  clearSearch() {
    this.value = null;
    this.descriptionValue = null;
    this._textInputDescriptionValue.value = null;
  }
  getCodLabel() {
    var _a;
    if (this.hideDescriptionInput) {
      return this.label;
    }
    return (_a = this.codLabel) !== null && _a !== void 0 ? _a : this.i18n("ez-search-plus.defaultCodeLabel");
  }
  async normalizeCodeToDescriptionValue(valueToNormalize) {
    if (!valueToNormalize) {
      return "";
    }
    if (typeof valueToNormalize == 'string') {
      try {
        valueToNormalize = JSON.parse(valueToNormalize);
        if ((valueToNormalize === null || valueToNormalize === void 0 ? void 0 : valueToNormalize.value) && !(valueToNormalize === null || valueToNormalize === void 0 ? void 0 : valueToNormalize.label)) {
          return await this.loadDescriptionValueByCode(valueToNormalize === null || valueToNormalize === void 0 ? void 0 : valueToNormalize.value);
        }
      }
      catch (e) {
        return await this.loadDescriptionValueByCode(valueToNormalize);
      }
    }
    //Se é diferente de objeto, temos que resolver a descrição
    if (typeof valueToNormalize != 'object') {
      return await this.loadDescriptionValueByCode(valueToNormalize);
    }
    return valueToNormalize === null || valueToNormalize === void 0 ? void 0 : valueToNormalize.label;
  }
  normalizeValueToCodeValue(valueToNormalize) {
    if (!valueToNormalize) {
      return undefined;
    }
    if (typeof valueToNormalize == 'string') {
      try {
        valueToNormalize = JSON.parse(valueToNormalize);
      }
      catch (e) {
        return valueToNormalize;
      }
    }
    if (typeof valueToNormalize != 'object') {
      return typeof valueToNormalize === 'number'
        ? String(valueToNormalize)
        : valueToNormalize;
    }
    return valueToNormalize === null || valueToNormalize === void 0 ? void 0 : valueToNormalize.value;
  }
  async loadDescriptionValueByCode(codeValue) {
    if (!this.optionLoader) {
      console.warn(this.i18n("ez-search-plus.optionLoaderNotDefined"));
      return "";
    }
    try {
      this.isLoadingDescription = true;
      const searchArgument = { mode: FormLayout.SearchMode.LOAD_DESCRIPTION, argument: codeValue };
      const loadedOption = await this.optionLoader(searchArgument);
      if (!loadedOption) {
        return "";
      }
      if (Array.isArray(loadedOption)) {
        return loadedOption[0].label;
      }
      return loadedOption.label;
    }
    finally {
      this.isLoadingDescription = false;
    }
  }
  handleCodeInputFocusOut() {
    this.cancelSelection();
    if (this.codeValue == this._textInputCodeValue.value)
      return;
    this.value = this._textInputCodeValue.value;
  }
  handleSearchClick() {
    this.loadAdvancedSearch();
  }
  async loadAdvancedSearch() {
    if (!this.optionLoader) {
      console.warn(this.i18n("ez-search-plus.optionLoaderNotDefined"));
      return;
    }
    const searchArgument = { mode: FormLayout.SearchMode.ADVANCED, argument: "" };
    let selectedItem = undefined;
    try {
      selectedItem = await this.optionLoader(searchArgument, this.contextProperties);
    }
    catch (ignore) { }
    if (!selectedItem)
      return;
    this.value = selectedItem;
  }
  buildCurrentValue() {
    if (core.StringUtils.isEmpty(this.codeValue)) {
      return undefined;
    }
    return {
      value: this.codeValue,
      label: this.descriptionValue
    };
  }
  async handleTextInputChangeHandler(event) {
    if (!this.searchDescriptionIsOpen) {
      this._popover.showUnder(this.el);
    }
    const argument = event.target.value;
    await this.debounceLoaderOptions(argument);
  }
  async debounceLoaderOptions(argument) {
    if (this._debounceSearch)
      clearTimeout(this._debounceSearch);
    return new Promise((resolve) => {
      this._debounceSearch = setTimeout(async () => {
        await this.processOptionsLoader(argument);
        resolve();
      }, this.SEARCH_DESCRIPTION_TIMEOUT);
    });
  }
  updateKeyOption(option) {
    return (Object.assign(Object.assign({}, option), { presentationValue: option.value, presentationLabel: option.label }));
  }
  parseSearchOptions(options = []) {
    if (Array.isArray(options)) {
      const firstOption = options[0];
      if (!firstOption) {
        return [];
      }
      if ("label" in firstOption || "value" in firstOption) {
        return options.map((option) => this.updateKeyOption(option));
      }
      return options;
    }
    if ("label" in options || "value" in options) {
      [this.updateKeyOption(options)];
    }
    return [options];
  }
  async processOptionsLoader(argument) {
    try {
      this.showLoading = true;
      const searchArgument = { mode: FormLayout.SearchMode.PREDICTIVE, argument };
      const options = await this.optionLoader(searchArgument);
      this.visibleOptions = this.parseSearchOptions(options);
    }
    finally {
      this.showLoading = false;
    }
  }
  handleSelectItem(evt) {
    const currentOpt = evt.detail;
    this.value = currentOpt;
    this._popover.hide();
    window.requestAnimationFrame(() => {
      var _a;
      (_a = this._textInputDescriptionValue) === null || _a === void 0 ? void 0 : _a.setFocus({ selectText: true });
    });
  }
  async handleArrowUp() {
    if (!this.isOptionsVisible()) {
      return;
    }
    await this._searchList.previousOption();
  }
  async handleArrowDown() {
    if (!this.isOptionsVisible()) {
      return;
    }
    await this._searchList.nextOption();
  }
  async selectCurrentItem() {
    var _a;
    await ((_a = this._searchList) === null || _a === void 0 ? void 0 : _a.selectCurrentItem());
  }
  async cancelSelection() {
    var _a, _b, _c;
    const description = typeof this.value === 'object' ? (_a = this.value) === null || _a === void 0 ? void 0 : _a.label : "";
    if (this._textInputDescriptionValue && description && this._textInputDescriptionValue.value != description) {
      this._textInputDescriptionValue.value = description;
    }
    await ((_b = this._searchList) === null || _b === void 0 ? void 0 : _b.cancelSelection());
    (_c = this._popover) === null || _c === void 0 ? void 0 : _c.hide();
  }
  async handleInputTab() {
    await this.cancelSelection();
  }
  async handleInputEsc() {
    var _a;
    await this.cancelSelection();
    await ((_a = this._latestFocusedInputElement) === null || _a === void 0 ? void 0 : _a.setFocus({ selectText: true }));
  }
  async initKeyboardManager() {
    this._keyboardManager = new core.KeyboardManager();
    const defaultOpts = { element: this.el, propagate: true };
    this._keyboardManager
      .bind("ArrowUp", () => this.handleArrowUp(), Object.assign(Object.assign({}, defaultOpts), { propagate: false }))
      .bind("ArrowDown", () => this.handleArrowDown(), Object.assign(Object.assign({}, defaultOpts), { propagate: false }))
      .bind("Enter", () => this.selectCurrentItem(), Object.assign(Object.assign({}, defaultOpts), { propagate: !this.stopPropagateEnterKeyEvent }))
      .bind("Tab", () => this.handleInputTab(), defaultOpts)
      .bind("Escape", () => this.handleInputEsc(), defaultOpts);
  }
  disconnectedCallback() {
    this._keyboardManager
      .unbind("ArrowUp")
      .unbind("ArrowDown")
      .unbind("Enter")
      .unbind("Tab")
      .unbind("Escape");
  }
  isOptionsVisible() {
    return this._popover.opened;
  }
  setLatestFocusedInputElement(el) {
    this._latestFocusedInputElement = el;
  }
  handleCodeInputFocus() {
    this.setLatestFocusedInputElement(this._textInputCodeValue);
  }
  handleDescriptionInputFocus() {
    this.setLatestFocusedInputElement(this._textInputDescriptionValue);
  }
  getRightIconElement() {
    var _a, _b;
    if (!this.ensureClearButtonVisible && (!this.value && !((_a = this._textInputCodeValue) === null || _a === void 0 ? void 0 : _a.value) && !((_b = this._textInputDescriptionValue) === null || _b === void 0 ? void 0 : _b.value))) {
      return null;
    }
    return index.h("button", { class: "btn btn__close", slot: "rightIcon", disabled: !this.enabled, tabindex: -1, onClick: () => this.clearSearch() }, index.h("ez-icon", { iconName: "close" }));
  }
  getLeftIconElement() {
    return index.h("button", { class: "btn", slot: "leftIcon", disabled: !this.enabled, tabindex: -1, onClick: () => this.handleSearchClick() }, this.canShowLoadSpinDescription() ? index.h("div", { class: "message__loading" }) : index.h("ez-icon", { iconName: "search" }));
  }
  handleOnEzVisibilityChange(event) {
    event.stopPropagation();
    this.searchDescriptionIsOpen = event.detail;
  }
  render() {
    core.ElementIDUtils.addIDInfoIfNotExists(this.el, 'input');
    return (index.h(index.Host, null, index.h("div", { class: "ez-search-plus__container" }, index.h("ez-text-input", { ref: elem => this._textInputCodeValue = elem, class: {
        "ez-search-plus__code-input": !this.hideDescriptionInput,
        "ez-search-plus__code-input-no-border": !this.hideDescriptionInput,
        "ez-search-plus__code-input-full": this.hideDescriptionInput
      }, "data-element-id": core.ElementIDUtils.getInternalIDInfo("codeInput"), "data-slave-mode": "true", enabled: !this.disableCodeInput && this.enabled, mode: this.mode, label: this.getCodLabel(), canShowError: this.canShowError, hasInvalid: !core.StringUtils.isEmpty(this.errorMessage), errorMessage: this.hideDescriptionInput ? this.errorMessage : "", value: this.codeValue, onFocusout: () => this.handleCodeInputFocusOut(), onFocus: () => this.handleCodeInputFocus() }, this.getLeftIconElement()), !this.hideDescriptionInput && (index.h("div", { class: "description-input-container" }, index.h("ez-text-input", { ref: elem => this._textInputDescriptionValue = elem, tabIndex: -1, class: "ez-search-plus__text-input", "data-element-id": core.ElementIDUtils.getInternalIDInfo("textInput"), "data-slave-mode": "true", enabled: !this.disableDescriptionInput && this.enabled, label: this.label, canShowError: this.canShowError, errorMessage: this.errorMessage, mode: this.mode, value: this.descriptionValue, onInput: event => this.handleTextInputChangeHandler(event), onFocus: () => this.handleDescriptionInputFocus() }, this.getRightIconElement()), index.h("ez-popover-plus", { ref: elem => this._popover = elem, anchorElement: this.el, autoClose: true, boxWidth: 'fit-content', overlayType: 'none', useAnchorSize: true, onEzVisibilityChange: (event) => this.handleOnEzVisibilityChange(event), "data-element-id": this.el.getAttribute("data-element-id") }, index.h("ez-search-result-list", { ref: (ref) => this._searchList = ref, showLoading: this.showLoading, visibleOptions: this.visibleOptions, value: this.value, showOptionValue: this.showOptionValue, onChangeValue: (evt) => this.handleSelectItem(evt) })))))));
  }
  get el() { return index.getElement(this); }
  static get watchers() { return {
    "value": ["observeValue"]
  }; }
};
EzSearchPlus.style = ezSearchPlusCss;

exports.ez_search_plus = EzSearchPlus;
