import "core-js/modules/es.error.cause.js";
import "core-js/modules/es.array.push.js";
function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
import { addClass, getScrollbarWidth } from "../../../helpers/dom/element.mjs";
import { clone, extend } from "../../../helpers/object.mjs";
import { isKey } from "../../../helpers/unicode.mjs";
import { partial } from "../../../helpers/function.mjs";
import { dataRowToChangesArray } from "../../../helpers/data.mjs";
import * as C from "../../../i18n/constants.mjs";
import { stopImmediatePropagation } from "../../../helpers/dom/event.mjs";
import { BaseUI } from "./_base.mjs";
import { InputUI } from "./input.mjs";
import { LinkUI } from "./link.mjs";
import { createArrayAssertion } from "../utils.mjs";
const SHORTCUTS_GROUP = 'multipleSelect.itemBox';

/**
 * @private
 * @class MultipleSelectUI
 */
var _items = /*#__PURE__*/new WeakMap();
var _itemsBox = /*#__PURE__*/new WeakMap();
var _locale = /*#__PURE__*/new WeakMap();
var _searchInput = /*#__PURE__*/new WeakMap();
var _selectAllUI = /*#__PURE__*/new WeakMap();
var _clearAllUI = /*#__PURE__*/new WeakMap();
var _MultipleSelectUI_brand = /*#__PURE__*/new WeakSet();
export class MultipleSelectUI extends BaseUI {
  static get DEFAULTS() {
    return clone({
      className: 'htUIMultipleSelect',
      value: []
    });
  }

  /**
   * List of available select options.
   *
   * @type {Array}
   */

  constructor(hotInstance, options) {
    super(hotInstance, extend(MultipleSelectUI.DEFAULTS, options));
    /**
     * 'input' event listener for input element.
     *
     * @param {Event} event DOM event.
     */
    _classPrivateMethodInitSpec(this, _MultipleSelectUI_brand);
    _classPrivateFieldInitSpec(this, _items, []);
    /**
     * Handsontable instance used as items list element.
     *
     * @type {Handsontable}
     */
    _classPrivateFieldInitSpec(this, _itemsBox, void 0);
    /**
     * A locale for the component used to compare filtered values.
     *
     * @type {string}
     */
    _classPrivateFieldInitSpec(this, _locale, void 0);
    /**
     * Input element.
     *
     * @type {InputUI}
     */
    _classPrivateFieldInitSpec(this, _searchInput, void 0);
    /**
     * "Select all" UI element.
     *
     * @type {LinkUI}
     */
    _classPrivateFieldInitSpec(this, _selectAllUI, void 0);
    /**
     * "Clear" UI element.
     *
     * @type {LinkUI}
     */
    _classPrivateFieldInitSpec(this, _clearAllUI, void 0);
    _classPrivateFieldSet(_searchInput, this, new InputUI(this.hot, {
      placeholder: C.FILTERS_BUTTONS_PLACEHOLDER_SEARCH,
      className: 'htUIMultipleSelectSearch'
    }));
    _classPrivateFieldSet(_selectAllUI, this, new LinkUI(this.hot, {
      textContent: C.FILTERS_BUTTONS_SELECT_ALL,
      className: 'htUISelectAll'
    }));
    _classPrivateFieldSet(_clearAllUI, this, new LinkUI(this.hot, {
      textContent: C.FILTERS_BUTTONS_CLEAR,
      className: 'htUIClearAll'
    }));
    this.registerHooks();
  }

  /**
   * Gets the instance of the internal Handsontable that acts here as a listbox component.
   *
   * @returns {Handsontable}
   */
  getItemsBox() {
    return _classPrivateFieldGet(_itemsBox, this);
  }

  /**
   * Register all necessary hooks.
   */
  registerHooks() {
    _classPrivateFieldGet(_searchInput, this).addLocalHook('keydown', event => _assertClassBrand(_MultipleSelectUI_brand, this, _onInputKeyDown).call(this, event));
    _classPrivateFieldGet(_searchInput, this).addLocalHook('input', event => _assertClassBrand(_MultipleSelectUI_brand, this, _onInput).call(this, event));
    _classPrivateFieldGet(_selectAllUI, this).addLocalHook('click', event => _assertClassBrand(_MultipleSelectUI_brand, this, _onSelectAllClick).call(this, event));
    _classPrivateFieldGet(_clearAllUI, this).addLocalHook('click', event => _assertClassBrand(_MultipleSelectUI_brand, this, _onClearAllClick).call(this, event));
  }

  /**
   * Set available options.
   *
   * @param {Array} items Array of objects with `checked` and `label` property.
   */
  setItems(items) {
    _classPrivateFieldSet(_items, this, items);
    if (_classPrivateFieldGet(_itemsBox, this)) {
      _classPrivateFieldGet(_itemsBox, this).loadData(_classPrivateFieldGet(_items, this));
    }
  }

  /**
   * Set a locale for the component.
   *
   * @param {string} locale Locale used for filter actions performed on data, ie. `en-US`.
   */
  setLocale(locale) {
    _classPrivateFieldSet(_locale, this, locale);
  }

  /**
   * Get a locale for the component.
   *
   * @returns {string}
   */
  getLocale() {
    return _classPrivateFieldGet(_locale, this);
  }

  /**
   * Get all available options.
   *
   * @returns {Array}
   */
  getItems() {
    return [..._classPrivateFieldGet(_items, this)];
  }

  /**
   * Get element value.
   *
   * @returns {Array} Array of selected values.
   */
  getValue() {
    return itemsToValue(_classPrivateFieldGet(_items, this));
  }

  /**
   * Gets the instance of the search input element.
   *
   * @returns {InputUI}
   */
  getSearchInputElement() {
    return _classPrivateFieldGet(_searchInput, this);
  }

  /**
   * Gets the instance of the "select all" link element.
   *
   * @returns {LinkUI}
   */
  getSelectAllElement() {
    return _classPrivateFieldGet(_selectAllUI, this);
  }

  /**
   * Gets the instance of the "clear" link element.
   *
   * @returns {LinkUI}
   */
  getClearAllElement() {
    return _classPrivateFieldGet(_clearAllUI, this);
  }

  /**
   * Check if all values listed in element are selected.
   *
   * @returns {boolean}
   */
  isSelectedAllValues() {
    return _classPrivateFieldGet(_items, this).length === this.getValue().length;
  }

  /**
   * Build DOM structure.
   */
  build() {
    super.build();
    const {
      rootDocument
    } = this.hot;
    const itemsBoxWrapper = rootDocument.createElement('div');
    const selectionControl = new BaseUI(this.hot, {
      className: 'htUISelectionControls',
      children: [_classPrivateFieldGet(_selectAllUI, this), _classPrivateFieldGet(_clearAllUI, this)]
    });
    this._element.appendChild(_classPrivateFieldGet(_searchInput, this).element);
    this._element.appendChild(selectionControl.element);
    this._element.appendChild(itemsBoxWrapper);
    const hotInitializer = wrapper => {
      if (!this._element) {
        return;
      }
      if (_classPrivateFieldGet(_itemsBox, this)) {
        _classPrivateFieldGet(_itemsBox, this).destroy();
      }
      addClass(wrapper, 'htUIMultipleSelectHot');
      // Constructs and initializes a new Handsontable instance
      _classPrivateFieldSet(_itemsBox, this, new this.hot.constructor(wrapper, {
        data: _classPrivateFieldGet(_items, this),
        columns: [{
          data: 'checked',
          type: 'checkbox',
          label: {
            property: 'visualValue',
            position: 'after'
          }
        }],
        beforeRenderer: (TD, row, col, prop, value, cellProperties) => {
          TD.title = cellProperties.instance.getDataAtRowProp(row, cellProperties.label.property);
        },
        afterListen: () => {
          this.runLocalHooks('focus', this);
        },
        beforeOnCellMouseUp: () => {
          _classPrivateFieldGet(_itemsBox, this).listen();
        },
        modifyColWidth: width => {
          const minWidth = _classPrivateFieldGet(_itemsBox, this).container.scrollWidth - getScrollbarWidth(rootDocument);
          if (width !== undefined && width < minWidth) {
            return minWidth;
          }
          return width;
        },
        hiddenRows: true,
        maxCols: 1,
        autoWrapCol: true,
        height: 110,
        copyPaste: false,
        disableVisualSelection: 'area',
        fillHandle: false,
        fragmentSelection: 'cell',
        tabMoves: {
          row: 1,
          col: 0
        },
        layoutDirection: this.hot.isRtl() ? 'rtl' : 'ltr'
      }));
      _classPrivateFieldGet(_itemsBox, this).init();
      const shortcutManager = _classPrivateFieldGet(_itemsBox, this).getShortcutManager();
      const gridContext = shortcutManager.getContext('grid');
      gridContext.removeShortcutsByKeys(['Tab']);
      gridContext.removeShortcutsByKeys(['Shift', 'Tab']);
      gridContext.addShortcut({
        keys: [['Escape']],
        callback: event => {
          this.runLocalHooks('keydown', event, this);
        },
        group: SHORTCUTS_GROUP
      });
      gridContext.addShortcut({
        keys: [['Tab'], ['Shift', 'Tab']],
        callback: event => {
          _classPrivateFieldGet(_itemsBox, this).deselectCell();
          this.runLocalHooks('keydown', event, this);
          this.runLocalHooks('listTabKeydown', event, this);
        },
        group: SHORTCUTS_GROUP
      });
    };
    hotInitializer(itemsBoxWrapper);
    this.hot._registerTimeout(() => hotInitializer(itemsBoxWrapper), 100);
  }

  /**
   * Focus element.
   */
  focus() {
    if (this.isBuilt()) {
      _classPrivateFieldGet(_itemsBox, this).listen();
    }
  }

  /**
   * Reset DOM structure.
   */
  reset() {
    _classPrivateFieldGet(_searchInput, this).reset();
    _classPrivateFieldGet(_selectAllUI, this).reset();
    _classPrivateFieldGet(_clearAllUI, this).reset();
  }

  /**
   * Update DOM structure.
   */
  update() {
    if (!this.isBuilt()) {
      return;
    }
    _classPrivateFieldGet(_itemsBox, this).loadData(valueToItems(_classPrivateFieldGet(_items, this), this.options.value));
    super.update();
  }

  /**
   * Destroy instance.
   */
  destroy() {
    if (_classPrivateFieldGet(_itemsBox, this)) {
      _classPrivateFieldGet(_itemsBox, this).destroy();
    }
    _classPrivateFieldGet(_searchInput, this).destroy();
    _classPrivateFieldGet(_clearAllUI, this).destroy();
    _classPrivateFieldGet(_selectAllUI, this).destroy();
    _classPrivateFieldSet(_searchInput, this, null);
    _classPrivateFieldSet(_clearAllUI, this, null);
    _classPrivateFieldSet(_selectAllUI, this, null);
    _classPrivateFieldSet(_itemsBox, this, null);
    _classPrivateFieldSet(_items, this, null);
    super.destroy();
  }
}
function _onInput(event) {
  const value = event.target.value.toLocaleLowerCase(this.getLocale());
  const hiddenRows = _classPrivateFieldGet(_itemsBox, this).getPlugin('hiddenRows');
  hiddenRows.showRows(hiddenRows.getHiddenRows());
  _classPrivateFieldGet(_items, this).forEach((item, index) => {
    item.checked = `${item.value}`.toLocaleLowerCase(this.getLocale()).indexOf(value) >= 0;
    if (!item.checked) {
      hiddenRows.hideRow(index);
    }
  });
  _classPrivateFieldGet(_itemsBox, this).view.adjustElementsSize();
  _classPrivateFieldGet(_itemsBox, this).render();
}
/**
 * 'keydown' event listener for input element.
 *
 * @param {Event} event DOM event.
 */
function _onInputKeyDown(event) {
  this.runLocalHooks('keydown', event, this);
  const isKeyCode = partial(isKey, event.keyCode);
  if (isKeyCode('ARROW_DOWN')) {
    event.preventDefault();
    stopImmediatePropagation(event);
    _classPrivateFieldGet(_itemsBox, this).listen();
    _classPrivateFieldGet(_itemsBox, this).selectCell(0, 0);
  }
}
/**
 * On click listener for "Select all" link.
 *
 * @param {DOMEvent} event The mouse event object.
 */
function _onSelectAllClick(event) {
  const changes = [];
  event.preventDefault();
  _classPrivateFieldGet(_itemsBox, this).getSourceData().forEach((row, rowIndex) => {
    row.checked = true;
    changes.push(dataRowToChangesArray(row, rowIndex)[0]);
  });
  _classPrivateFieldGet(_itemsBox, this).setSourceDataAtCell(changes);
}
/**
 * On click listener for "Clear" link.
 *
 * @param {DOMEvent} event The mouse event object.
 */
function _onClearAllClick(event) {
  const changes = [];
  event.preventDefault();
  _classPrivateFieldGet(_itemsBox, this).getSourceData().forEach((row, rowIndex) => {
    row.checked = false;
    changes.push(dataRowToChangesArray(row, rowIndex)[0]);
  });
  _classPrivateFieldGet(_itemsBox, this).setSourceDataAtCell(changes);
}
export default MultipleSelectUI;

/**
 * Pick up object items based on selected values.
 *
 * @param {Array} availableItems Base collection to compare values.
 * @param {Array} selectedValue Flat array with selected values.
 * @returns {Array}
 */
function valueToItems(availableItems, selectedValue) {
  const arrayAssertion = createArrayAssertion(selectedValue);
  return availableItems.map(item => {
    item.checked = arrayAssertion(item.value);
    return item;
  });
}

/**
 * Convert all checked items into flat array.
 *
 * @param {Array} availableItems Base collection.
 * @returns {Array}
 */
function itemsToValue(availableItems) {
  const items = [];
  availableItems.forEach(item => {
    if (item.checked) {
      items.push(item.value);
    }
  });
  return items;
}