var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { h } from '@stencil/core';
import { MapToComponentField, MapToComponentMethod, VegaSlimmer } from 'vega-slimmer/core';
import { DomNodeSubjectObserverFactory } from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import changeManager from '../../../../helpers/change-manager/change-manager';
import domNodeSubjectFactory from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-factory';
import { VegaInternalDropdownTemplateItemsChange, VegaInternalUpdateVegaInputValue, } from '../../../../helpers/event-manager/event-id/vega-internal-event-id';
import { VegaDropdownClick } from '../../../../helpers/event-manager/event-id/vega-event-id';
import { ClickOutsideOnlyToDismissStrategy } from '../../../../helpers/slimmers/element-appender/trigger-strategies/click-outside-only-to-dismiss-strategy';
/**
 * Renderer class for the Vega App Header Button Dropdown.
 * This class extends the VegaSlimmer and is responsible for rendering the dropdown component and managing its state and events.
 */
export class VegaInputInputSuggestionsRenderer extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.templateItems = [];
    /**
     * emit dropdown click event when component get dropdown item click
     *
     * @param {NotifyObserverPayload<string>} input the click detail
     */
    this.onDropdownItemClick = async (input) => {
      const items = this.renderModeController.isTemplate()
        ? this.templateItems
        : this.suggestionsDropdownSource;
      const item = this.findItem(items, input.detail);
      if (item) {
        const event = this.suggestionItemClickEventEmitter.emit(item);
        changeManager.notify(domNodeSubjectFactory.getSubject(this.host, VegaInternalUpdateVegaInputValue), event.defaultPrevented ? this.value : item.label);
      }
    };
  }
  appendHostItemsToDropdown() {
    if (this.renderModeController.isTemplate() && this.itemsSlotRef && this.dropdownRef) {
      this.itemsSlotRef.remove();
      this.dropdownRef.append(this.host.querySelector('[slot=items]'));
    }
  }
  async showSuggestionsDropdown(dropdownConfig = {}) {
    this.suggestionsDropdownConfig = dropdownConfig;
    await this.showSuggestions();
  }
  async hideSuggestionsDropdown() {
    await this.dropdownRef.hide();
  }
  async watchValue() {
    await this.searchSuggestions();
  }
  async watchSuggestionsDropdownSource() {
    await this.searchSuggestions();
  }
  /**
   * Renders the dropdown component with the provided children.
   *
   * @param {HTMLElement} children HTML element children to be rendered inside the dropdown.
   * @returns {HTMLElement} The rendered dropdown component.
   */
  render(children) {
    return (h("vega-dropdown", Object.assign({}, this.suggestionsDropdownConfig, { source: this.suggestionsDropdownSource, trigger: new ClickOutsideOnlyToDismissStrategy(), matchTargetWidth: true, searchable: false, placement: ['top', 'bottom'], translocation: { X: 0, Y: 6 }, ref: (ref) => {
        this.dropdownRef = ref;
        this.addDropdownObserver(ref);
      }, style: { display: 'block' } }),
      children,
      this.renderItemsSlot()));
  }
  renderItemsSlot() {
    return (this.renderModeController.isTemplate() && (h("div", { slot: "items", ref: (ref) => {
        this.itemsSlotRef = ref;
      } })));
  }
  addDropdownObserver(ref) {
    DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaDropdownClick, this.onDropdownItemClick.bind(this));
    DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaInternalDropdownTemplateItemsChange, (payload) => {
      this.templateItems = Array.from(payload).map((item) => ({
        key: item.itemKey,
        label: item.label,
      }));
    });
  }
  findItem(source, key) {
    for (const item of source) {
      if (item['children'] && item['children'].length > 0) {
        const found = this.findItem(item['children'], key);
        if (found)
          return found;
      }
      if (item.key.toString() === key)
        return item;
    }
    /* istanbul ignore next */
    return null;
  }
  async showSuggestions() {
    if (this.dropdownRef &&
      (this.renderModeController.isSource() || this.renderModeController.isTemplate())) {
      await this.dropdownRef.show();
    }
  }
  async searchSuggestions() {
    if (this.dropdownRef &&
      this.renderModeController.isSource() &&
      this.suggestionsDropdownSource.length > 0) {
      await this.dropdownRef.search(this.value);
    }
  }
}
__decorate([
  MapToComponentField()
], VegaInputInputSuggestionsRenderer.prototype, "host", void 0);
__decorate([
  MapToComponentField()
], VegaInputInputSuggestionsRenderer.prototype, "value", void 0);
__decorate([
  MapToComponentField({ writable: true })
], VegaInputInputSuggestionsRenderer.prototype, "suggestionsDropdownConfig", void 0);
__decorate([
  MapToComponentField()
], VegaInputInputSuggestionsRenderer.prototype, "suggestionsDropdownSource", void 0);
__decorate([
  MapToComponentField()
], VegaInputInputSuggestionsRenderer.prototype, "renderModeController", void 0);
__decorate([
  MapToComponentField()
], VegaInputInputSuggestionsRenderer.prototype, "suggestionItemClickEventEmitter", void 0);
__decorate([
  MapToComponentMethod('componentDidLoad')
], VegaInputInputSuggestionsRenderer.prototype, "appendHostItemsToDropdown", null);
__decorate([
  MapToComponentMethod('showSuggestionsDropdown')
], VegaInputInputSuggestionsRenderer.prototype, "showSuggestionsDropdown", null);
__decorate([
  MapToComponentMethod('hideSuggestionsDropdown')
], VegaInputInputSuggestionsRenderer.prototype, "hideSuggestionsDropdown", null);
__decorate([
  MapToComponentMethod('watchValue')
], VegaInputInputSuggestionsRenderer.prototype, "watchValue", null);
__decorate([
  MapToComponentMethod('watchSuggestionsDropdownSource')
], VegaInputInputSuggestionsRenderer.prototype, "watchSuggestionsDropdownSource", null);
