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 { MapToComponentField, MapToComponentMethod, VegaSlimmer } from 'vega-slimmer/core';
import { extractNumberFromString } from '../../../../utils/ui';
import { LogUtility } from '../../../../utils/log';
import ChangeManager from '../../../../helpers/change-manager/change-manager';
import { SHADOW_ROOT_ELEMENT_SCROLLING } from '../../../../helpers/change-manager/subject/static-subject/static-subject-title';
/**
 * The `VegaDropdownScrollableController` class in TypeScript manages the behavior of a scrollable dropdown component,
 * adjusting list container height and scrolling to specific indexes based on render mode and selected source key.
 */
export class VegaDropdownScrollableController extends VegaSlimmer {
  constructor() {
    super(...arguments);
    /*
     * The below method is e2e-test covered in
     * @see{module:vega-dropdown-shadow-root-scroll-e2e}
     */
    /* istanbul ignore next */
    /**
     * Listen scrolling of dropdown content
     */
    this.onScroll = () => {
      !this.renderModeController.isSourceRenderMode() &&
        ChangeManager.notify(SHADOW_ROOT_ELEMENT_SCROLLING, {
          host: this.renderer.getDropdownContentBoxRef(),
        });
    };
  }
  /**
   * The function `watchIsDropdownShow` adjusts the list container height and scrolls to a specific index
   * if the dropdown is shown in a certain render mode.
   */
  async watchIsDropdownShow() {
    if (this.isDropdownShow) {
      this.adjustListContainerMaxHeight();
      await this.scrollToSelectedIndex();
    }
  }
  /**
   * While resettable, we should listen selected key to decide adjust max height of list container.
   *
   * @param {string[] | string} newValue - new value.
   * @param {string[] | string} oldValue - old value.
   */
  watchSelectedSourceKey(newValue, oldValue) {
    if (this.resettable &&
      ((newValue && newValue.length > 0 && (!oldValue || oldValue.length === 0)) ||
        ((!newValue || newValue.length === 0) && oldValue && oldValue.length > 0))) {
      this.adjustListContainerMaxHeight();
    }
  }
  /**
   * The function scrollToSelected asynchronously scrolls to a selected index based on the render mode.
   */
  async scrollToSelectedIndex() {
    this.renderModeController.isSourceRenderMode()
      ? await this.scrollToVirtualIndex()
      : this.scrollToTemplateIndex();
  }
  /**
   * The function scrollToVirtualIndex asynchronously scrolls to a specific index in a virtual list based
   * on the selected key.
   */
  async scrollToVirtualIndex() {
    const index = this.sourceForRender.findIndex((item) => item.key === this.getSelectedKey());
    index >= 0 && (await this.listRenderer.getVirtualScrollRef().scrollToIndex(index));
  }
  /*
   * The below method is e2e-test covered in
   * @see{module:vega-dropdown-scroll-to-selected-key-in-single-template-e2e}
   * @see{module:vega-dropdown-scroll-to-selected-key-in-multiple-template-e2e}
   */
  /* istanbul ignore next */
  /**
   * The function scrollToTemplateIndex scrolls the dropdown content box to the selected item key.
   */
  scrollToTemplateIndex() {
    const scrolledKey = this.getSelectedKey();
    if (scrolledKey) {
      const dropdownContent = this.renderer.getDropdownContentBoxRef();
      const selectedItem = dropdownContent.querySelector(`vega-dropdown-item[item-key='${scrolledKey}']`);
      if (selectedItem) {
        const ul = dropdownContent.shadowRoot.querySelector('ul');
        const ulRect = ul.getBoundingClientRect();
        const itemRect = selectedItem.getBoundingClientRect();
        ul.scrollTop = itemRect.top - ulRect.top + ul.scrollTop;
      }
    }
  }
  /**
   * The function `getSelectedKey` returns the selected key based on the `selectType` condition.
   *
   * @returns {string} The `getSelectedKey` method returns a string value. If `this.selectType` is equal to
   * 'multiple', it returns the first element of the `selectedSourceKey` array as a string. Otherwise, it
   * returns the `selectedSourceKey` value as a string.
   */
  getSelectedKey() {
    return this.selectType === 'multiple'
      ? this.selectedSourceKey[0]
      : this.selectedSourceKey;
  }
  /*
   * The below method is e2e-test covered in
   * @see{module:vega-dropdown-with-matchContainerHeight-e2e}
   * @see{module:vega-dropdown-without-matchContainerHeight-e2e}
   */
  /* istanbul ignore next */
  /**
   * we only calculate surplus space of bottom, we should calculate maxHeight more accurately here.
   * such as minus the gap of dropdown, the dropdown padding top and bottom, the gap of bottom.
   * if with searchable, we should minus the height of searchable.
   * if the dropdown in the top of host, we should only minus top of distance from vega-dropdown to vega-dropdown-container.
   */
  adjustListContainerMaxHeight() {
    const dropdownRef = this.renderer.getDropdownContentBoxRef();
    if (!dropdownRef)
      return;
    const dropdownMaxHeight = extractNumberFromString(dropdownRef.style.maxHeight);
    const searchActionContentHeight = this.searchable
      ? VegaDropdownScrollableController.actionButtonContentHeight
      : 0;
    const resetActionContentHeight = this.resettable && this.selectedSourceKey.length > 0
      ? VegaDropdownScrollableController.actionButtonContentHeight
      : 0;
    const layoutSpaceSpace = dropdownRef.classList.contains('vega-placement-top')
      ? 0
      : VegaDropdownScrollableController.dropdownLayoutSpaceHeight;
    const height = dropdownMaxHeight - searchActionContentHeight - layoutSpaceSpace - resetActionContentHeight;
    if (height <= 40) {
      this.setItemsContainerMaxHeight(40);
      LogUtility.error("There have no space on the bottom to display dropdown, if you want to adjust position, you should make 'match-container-height' as false.");
    }
    else {
      this.setItemsContainerMaxHeight(height);
    }
  }
  /**
   * The function `setItemsContainerMaxHeight` adjusts the maximum height of the items container based on
   * the render mode.
   *
   * @param {number} maxHeight - The `maxHeight` parameter is a number that represents the maximum height
   * in pixels that the items container should have.
   */
  setItemsContainerMaxHeight(maxHeight) {
    if (this.renderModeController.isSourceRenderMode()) {
      this.listRenderer.getVirtualScrollRef().viewportMaxHeight = maxHeight;
    }
    else {
      const templateContainerRef = this.listRenderer.getTemplateContainerRef();
      templateContainerRef.style.overflowY = 'auto';
      templateContainerRef.style.maxHeight = `${maxHeight}px`;
    }
  }
}
VegaDropdownScrollableController.actionButtonContentHeight = 49; // actionHeight(40) + dividerHeight(paddingY + dividerHeight = 9);
VegaDropdownScrollableController.dropdownLayoutSpaceHeight = 10; // paddingY + borderY;
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "isDropdownShow", void 0);
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "renderModeController", void 0);
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "sourceForRender", void 0);
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "selectType", void 0);
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "selectedSourceKey", void 0);
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "searchable", void 0);
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "listRenderer", void 0);
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "renderer", void 0);
__decorate([
  MapToComponentField()
], VegaDropdownScrollableController.prototype, "resettable", void 0);
__decorate([
  MapToComponentMethod('watchIsDropdownShow')
], VegaDropdownScrollableController.prototype, "watchIsDropdownShow", null);
__decorate([
  MapToComponentMethod('watchSelectedSourceKey')
], VegaDropdownScrollableController.prototype, "watchSelectedSourceKey", null);
