'use strict';

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

const index = require('./index-1894343a.js');
const core = require('@sankhyalabs/core');

const snkEntitySearchCss = ".entity-search-popover{width:432px;font-family:var(--font-pattern, \"Roboto\");color:var(--color--gray-600, #1C1D22);text-shadow:0 0 var(--color--gray-500, #494A4E), 0 0 1px transparent;font-size:var(--font-size--large, 18px);padding:var(--space--24, 24px);max-width:430px;display:flex;flex-direction:column}.entity-search-popover label{margin-bottom:var(--space--16, 16px)}";

const SnkEntitySearch = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.loaded = index.createEvent(this, "loaded", 7);
    this.SEARCH_DESCRIPTION_TIMEOUT = 300;
    this._entityPKField = null;
    this.searchEntitySelect = async (item) => {
      if (!this._entityPKField || !item) {
        return;
      }
      try {
        const pk = [{ name: this._entityPKField, value: item.value }];
        await this.closeSearchPopover();
        await this.refreshDataUnitByPk(pk);
      }
      catch (error) {
        console.error('Erro ao selecionar entidade:', error);
      }
    };
    this.entityName = "";
    this.dataUnit = undefined;
    this.messagesBuilder = undefined;
    this._searchInputValue = "";
    this._showMoreOnSearch = false;
    this.visibleOptions = [];
    this.value = undefined;
    this.showLoading = true;
  }
  async showUnder(element) {
    await this._popoverSearchEntity.showUnder(element, { horizontalGap: 12, verticalGap: 4 });
  }
  buildSearchOptions(limit) {
    return {
      entity: this.entityName,
      entityDescription: this.entityName,
      executeOnOpen: true,
      searchOptions: {
        localEntityName: this.entityName,
        limit,
      }
    };
  }
  async handlePredictiveSearch(argument) {
    var _a, _b;
    const response = await this._application.executePreparedSearchWithFullResponse(argument, this.buildSearchOptions(5));
    this._showMoreOnSearch = (_a = response === null || response === void 0 ? void 0 : response.hasMore) !== null && _a !== void 0 ? _a : false;
    this._entityPKField = response === null || response === void 0 ? void 0 : response.pkField;
    return (_b = response === null || response === void 0 ? void 0 : response.data) !== null && _b !== void 0 ? _b : [];
  }
  async loadEntitySuggestions(argument) {
    var _a;
    const value = (_a = argument === null || argument === void 0 ? void 0 : argument.argument) !== null && _a !== void 0 ? _a : '';
    const mode = (argument === null || argument === void 0 ? void 0 : argument.mode) || "PREDICTIVE";
    if (!value || value.trim().length === 0) {
      return [];
    }
    try {
      this._showMoreOnSearch = false;
      if (mode === "PREDICTIVE") {
        return await this.handlePredictiveSearch(value);
      }
      const searchResult = await this._application.executePreparedSearch(mode, value, this.buildSearchOptions());
      return Array.isArray(searchResult) ? searchResult : [searchResult];
    }
    catch (error) {
      console.error('Erro ao carregar sugestões de entidades:', error);
      return [];
    }
  }
  async refreshDataUnitByPk(pks) {
    try {
      const pkField = pks[0].name;
      const pkValue = pks[0].value;
      // Criar filtro para a busca específica
      const quickFilter = {
        term: '',
        filter: {
          name: '',
          params: [],
          expression: `(${pkField} = ${pkValue})`
        }
      };
      // Carregar dados com o filtro aplicado diretamente
      await this.dataUnit.loadData(quickFilter);
      this.loaded.emit(this.dataUnit.records);
    }
    catch (error) {
      console.error('Erro ao atualizar dataset:', error);
    }
  }
  async closeSearchPopover() {
    if (this._popoverSearchEntity && this._popoverSearchEntity.opened) {
      await this._popoverSearchEntity.hide();
    }
  }
  async handleOnEzVisibilityChange(event) {
    if (event.detail) {
      await this._textInput.setFocus();
    }
  }
  async handleSelectItem(evt) {
    const currentOpt = evt.detail;
    this.value = currentOpt;
    await this._popoverListResult.hide();
    await this.searchEntitySelect(currentOpt);
    this._searchInputValue = "";
  }
  updateKeyOption(option) {
    return (Object.assign(Object.assign({}, option), { presentationValue: option.value, presentationLabel: option.label }));
  }
  async handleInputChange(value) {
    if (this._debounceSearch) {
      clearTimeout(this._debounceSearch);
    }
    return new Promise((resolve) => {
      this._debounceSearch = setTimeout(async () => {
        var _a;
        this.showLoading = true;
        this._searchInputValue = value;
        await this._popoverListResult.showUnder(this._textInput);
        this.visibleOptions = (_a = (await this.loadEntitySuggestions({ argument: this._searchInputValue, mode: undefined }))) === null || _a === void 0 ? void 0 : _a.map(this.updateKeyOption);
        this.showLoading = false;
        resolve();
      }, this.SEARCH_DESCRIPTION_TIMEOUT);
    });
  }
  isOptionsVisible() {
    return this._popoverListResult.opened;
  }
  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;
    await ((_a = this._searchList) === null || _a === void 0 ? void 0 : _a.cancelSelection());
    (_b = this._popoverListResult) === null || _b === void 0 ? void 0 : _b.hide();
  }
  async handleInputTab() {
    await this.cancelSelection();
  }
  async handleInputEsc() {
    await this.cancelSelection();
  }
  getMessage(key, params) {
    if (this.messagesBuilder) {
      return this.messagesBuilder.getMessage(key, params);
    }
    // Fallback para mensagens padrão em português
    const messages = {
      'snkCrud.entitySearch.label': 'Busca por registros',
      'snkCrud.entitySearch.placeholder': 'Digite o que você procura aqui...'
    };
    return messages[key] || key;
  }
  async initKeyboardManager() {
    this._keyboardManager = new core.KeyboardManager();
    const defaultOpts = { element: this._elem, 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: false }))
      .bind("Tab", () => this.handleInputTab(), defaultOpts)
      .bind("Escape", () => this.handleInputEsc(), defaultOpts);
  }
  connectedCallback() {
    this.initKeyboardManager();
  }
  componentWillLoad() {
    this._application = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  componentDidLoad() {
    core.ElementIDUtils.addIDInfoIfNotExists(this._elem, 'snk-entity-search');
  }
  disconnectedCallback() {
    this._keyboardManager
      .unbind("ArrowUp")
      .unbind("ArrowDown")
      .unbind("Enter")
      .unbind("Tab")
      .unbind("Escape");
  }
  render() {
    return (index.h(index.Host, null, index.h("ez-popover-core", { ref: (ref) => this._popoverSearchEntity = ref, onEzVisibilityChange: (event) => this.handleOnEzVisibilityChange(event) }, index.h("div", { class: "entity-search-popover" }, index.h("label", null, this.getMessage('snkCrud.entitySearch.label')), index.h("ez-classic-input", { ref: (ref) => this._textInput = ref, placeholder: this.getMessage('snkCrud.entitySearch.placeholder'), rightIconClickable: true, size: "small", value: this._searchInputValue, onEzChange: (evt) => this.handleInputChange(evt.detail) }), index.h("ez-popover-core", { ref: elem => this._popoverListResult = elem, anchorElement: this._textInput, autoClose: true, boxWidth: 'fit-content', overlayType: 'none', useAnchorSize: true, onEzVisibilityChange: (event) => event.stopPropagation() }, index.h("ez-search-result-list", { ref: (ref) => this._searchList = ref, showLoading: this.showLoading, visibleOptions: this.visibleOptions, value: this.value, onChangeValue: (evt) => this.handleSelectItem(evt) }))))));
  }
  get _elem() { return index.getElement(this); }
};
SnkEntitySearch.style = snkEntitySearchCss;

exports.snk_entity_search = SnkEntitySearch;
