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 { Fragment, h } from '@stencil/core';
import { MapToComponentField, MapToComponentMethod, VegaSlimmer } from 'vega-slimmer/core';
import { createEnterKeyHandlerToTriggerClick } from '../../../../utils/accessibility';
import { DomNodeSubjectObserverFactory } from '../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-observer-factory';
import { VegaClose, VegaCreate, VegaDropdownClick, VegaDropdownHide, } from '../../../../helpers/event-manager/event-id/vega-event-id';
import { VegaInternalDropdownTemplateItemsChange } from '../../../../helpers/event-manager/event-id/vega-internal-event-id';
import { htmlSanitizer, labelSanitizeStrategy } from '../../../../utils/sanitize';
export class VegaComboBoxDropdownRenderer extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.onItemClick = async () => {
      this.valueController.setValue((await this.dropdownRef.getSelection()));
      await this.clearInput();
    };
    this.onDropdownHide = async () => {
      await this.clearInput();
    };
    this.onDropdownCreate = async (searchString) => {
      this.createEventEmit.emit(searchString);
      await this.clearInput();
    };
    /**
     * The below method is e2e-test covered in
     * @see{module:vega-combo-box-search-input}
     * @see{module:vega-combo-box-vega-search-event-e2e}
     */
    /* istanbul ignore next */
    this.onInputChange = async (e) => {
      const value = e.target.value;
      if (this.useDefaultFilter || this.vegaDropdownProps.dynamicOption) {
        await this.dropdownRef.show();
        await this.dropdownRef.search(value);
      }
      if (this.isTemplateMode || !this.useDefaultFilter) {
        this.searchEventEmit.emit(value);
      }
    };
  }
  connectedCallback() {
    this.isTemplateMode = this.host.querySelector('[slot=items]') !== null;
  }
  getDropdownRef() {
    return this.dropdownRef;
  }
  getSearchInputRef() {
    return this.searchInputRef;
  }
  /**
   * The below method is e2e-test covered in
   * @see{module:vega-combo-box-focus-by-label-e2e}
   */
  /* istanbul ignore next */
  focusInput() {
    this.searchInputRef.focus();
  }
  async hide() {
    await this.dropdownRef.hide();
  }
  async show() {
    await this.dropdownRef.show();
  }
  replaceItemsSlot(itemsSlot) {
    if (itemsSlot && this.itemsSlotRef) {
      this.itemsSlotRef.remove();
      this.dropdownRef.append(itemsSlot);
    }
  }
  renderDropdown() {
    return (h("vega-dropdown", Object.assign({ trigger: this.disabled ? 'none' : 'click', source: this.source, selectType: "multiple", selectedSourceKey: this.value, matchTargetWidth: true, useDefaultFilter: this.useDefaultFilter }, this.vegaDropdownProps, { ref: (ref) => {
        this.dropdownRef = ref;
        DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaCreate, async (payload) => {
          await this.onDropdownCreate(payload.detail);
        });
        DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaDropdownHide, async () => {
          await this.onDropdownHide();
        });
        DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaDropdownClick, async () => {
          await this.onItemClick();
        });
        DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaInternalDropdownTemplateItemsChange, 
        /*
         * The below method is e2e-test covered in
         * @see{module:vega-combo-box-template-select-e2e}
         */
        /* istanbul ignore next */
        (payload) => {
          const addedItems = Array.from(payload)
            .filter((item) => !this.source.find((sourceItem) => sourceItem.key === item.itemKey))
            .map((item) => ({
            key: item.itemKey,
            label: item.label,
          }));
          this.sourceController.setSource([...this.source, ...addedItems]);
        });
      } }),
      this.renderContainer(),
      this.renderItemsSlot()));
  }
  renderContainer() {
    return (h("div", { class: {
        'vega-combo-box-container': true,
        [`vega-combo-box-size-${this.size}`]: true,
      } },
      this.renderSelectedContainer(),
      this.renderInputContainer()));
  }
  renderItemsSlot() {
    return (this.isTemplateMode && (h("div", { slot: "items", ref: (ref) => {
        this.itemsSlotRef = ref;
      } })));
  }
  renderSelectedContainer() {
    const selected = this.value
      .map((key) => this.source.find((item) => item.key === key))
      .filter((item) => item);
    return (h(Fragment, null, selected.map((item) => {
      return this.renderSelectedChip(item);
    })));
  }
  renderSelectedChip(item) {
    return (h("vega-chip", { 
      //TODO: the key property test will add in https://gethired.atlassian.net/browse/VD-883
      key: item.key, text: htmlSanitizer.sanitize(item.label, labelSanitizeStrategy), variant: "outlined", showCloseIcon: !this.disabled, size: "small", ref: (ref) => {
        DomNodeSubjectObserverFactory.addUniqueObserverToNode(ref, VegaClose, async () => {
          await this.onChipClose(item.key);
        });
      } }));
  }
  renderInputContainer() {
    return (h("div", { class: "vega-combo-box-input-container" },
      h("input", { onInput: this.onInputChange, "aria-label": this.label || 'No label defined', placeholder: this.value.length === 0 ? this.placeholder : '', ref: (e) => (this.searchInputRef = e), onKeyDown: createEnterKeyHandlerToTriggerClick(), disabled: this.disabled })));
  }
  async onChipClose(key) {
    this.valueController.setValue([...this.value.filter((value) => value !== key)]);
    await this.dropdownRef.hide();
  }
  async clearInput() {
    this.searchInputRef.value = '';
    await this.dropdownRef.search('');
  }
}
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "host", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "value", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "source", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "disabled", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "size", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "vegaDropdownProps", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "label", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "placeholder", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "useDefaultFilter", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "createEventEmit", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "searchEventEmit", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "valueController", void 0);
__decorate([
  MapToComponentField()
], VegaComboBoxDropdownRenderer.prototype, "sourceController", void 0);
__decorate([
  MapToComponentMethod('connectedCallback')
], VegaComboBoxDropdownRenderer.prototype, "connectedCallback", null);
