import { r as registerInstance, c as createEvent, h, H as Host } from './index-baa5e267.js';
import { ObjectUtils } from '@sankhyalabs/core';
import { i as isContinuousSequence } from './ezListHelper-00fb9b8d.js';
import { i as initI18n } from './index-41363fa6.js';

function moveItems(selectedItemsList, itemsList, foward) {
  if (!selectedItemsList.length)
    return [...itemsList];
  if (!itemsList.length)
    return [];
  const selectedIndexes = getItemsIndex(selectedItemsList, itemsList);
  const startIndex = getMinValue(selectedIndexes);
  const endIndex = getMaxValue(selectedIndexes);
  return moveRange(startIndex, endIndex, foward, itemsList);
}
function getMinValue(numbers) {
  if (numbers.length === 0)
    return 0;
  return numbers.reduce((min, current) => (current < min ? current : min), numbers[0]);
}
function getMaxValue(numbers) {
  if (numbers.length === 0)
    return 0;
  return numbers.reduce((max, current) => (current > max ? current : max), numbers[0]);
}
function getItemsIndex(selectedItemsList, itemsList) {
  return selectedItemsList.map(selectedId => itemsList.findIndex(original => original.id === selectedId));
}
function moveRange(startIndex, endIndex, moveForward, listItem) {
  if (startIndex < 0 || endIndex >= listItem.length || startIndex > endIndex)
    return listItem;
  if (moveForward)
    return moveFoward(endIndex, startIndex, listItem);
  return moveBackward(startIndex, endIndex, listItem);
}
function moveBackward(startIndex, endIndex, listItem) {
  if (startIndex === 0)
    return listItem;
  const beforeRange = listItem.slice(0, startIndex - 1);
  const range = listItem.slice(startIndex, endIndex + 1);
  const afterRange = listItem.slice(endIndex + 1);
  const movedItem = listItem[startIndex - 1];
  return [...beforeRange, ...range, movedItem, ...afterRange];
}
function moveFoward(endIndex, startIndex, listItem) {
  if (endIndex === listItem.length - 1)
    return listItem;
  const beforeRange = listItem.slice(0, startIndex);
  const range = listItem.slice(startIndex, endIndex + 1);
  const afterRange = listItem.slice(endIndex + 1);
  const movedItem = afterRange.shift();
  return movedItem
    ? [...beforeRange, movedItem, ...range, ...afterRange]
    : listItem;
}
function transferAll({ from, to, selectedFrom, selectedTo }) {
  to = [...to.map(i => setItemSelection(i, false)), ...from.map(i => setItemSelection(i, true))];
  selectedFrom = [];
  selectedTo = [...from.map(({ id }) => id)];
  from = [];
  return { from, to, selectedFrom, selectedTo };
}
function transferItems({ from, to, selectedFrom, selectedTo, insertIndex = to.length, }) {
  if (!from.length)
    return { from, to, selectedFrom, selectedTo };
  const itemsToTransfer = getItemsToTransfer(to, selectedFrom, from);
  if (!itemsToTransfer.length)
    return { from, to, selectedFrom, selectedTo };
  let updatedTo = to.map(i => setItemSelection(i, false));
  updatedTo.splice(insertIndex, 0, ...itemsToTransfer.map(i => setItemSelection(i, true)));
  return {
    from: from.filter(item => !selectedFrom.includes(item.id)),
    to: updatedTo,
    selectedFrom: [],
    selectedTo: [...selectedFrom],
  };
}
function getItemsToTransfer(to, selectedFrom, from) {
  const toListIds = to.map(item => item.id);
  //Não deve transferir um item que já existe na lista destino
  const itemsToTransferId = selectedFrom.filter((id) => !toListIds.includes(id));
  return from.filter(({ id }) => itemsToTransferId.includes(id));
}
function setItemSelection(item, select) {
  return Object.assign(Object.assign({}, item), { selected: select });
}

const ezDoubleListCss = ".sc-ez-double-list-h{display:flex;flex-direction:row;gap:8px;align-items:center;font-family:var(--font-pattern, \"Roboto\");width:100%}@media screen and (max-width: 1366px){.group.sc-ez-double-list{height:350px}}.list__container.sc-ez-double-list{height:100%;width:100%;min-height:150px;overflow:auto;display:flex}.actions__column.sc-ez-double-list{display:flex;flex-direction:column;gap:4px}";

const EzDoubleList = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezLeftListChanged = createEvent(this, "ezLeftListChanged", 7);
    this.ezRightListChanged = createEvent(this, "ezRightListChanged", 7);
    this.LEFT_LIST_ID = 'LEFT-LIST-ID';
    this.RIGHT_LIST_ID = 'RIGHT-LIST-ID';
    this.leftList = [];
    this.leftTitle = undefined;
    this.rightList = [];
    this.entityLabel = 'item';
    this.entityLabelPlural = 'itens';
    this.leftListLabel = 'disponíveis';
    this.rightListLabel = 'selecionados';
    this.useOnlyRightList = false;
    this.rightTitle = undefined;
    this.emptyMessage = undefined;
    this.slotsListBuilder = undefined;
    this.leftFilteredList = [];
    this.rightFilteredList = [];
    this.selectedLeftList = [];
    this.selectedRightList = [];
    this.isFilteringLeft = false;
    this.isFilteringRight = false;
  }
  async resetSelectedLists() {
    this.selectedLeftList = [];
    this.selectedRightList = [];
  }
  observeLeftList(newValue, oldValue) {
    if (ObjectUtils.equals(newValue, oldValue))
      return;
    this.ezLeftListChanged.emit(newValue);
  }
  observeRightList(newValue, oldValue) {
    if (ObjectUtils.equals(newValue, oldValue))
      return;
    this.ezRightListChanged.emit(newValue);
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  async handleChangeLeft({ detail }) {
    if (!detail.to.getAttribute('id') || detail.to.getAttribute('id') !== this.RIGHT_LIST_ID) {
      this.leftList = [...this.reorderArray(detail.dataSource, detail.selectItens, detail.newIndex)];
      return;
    }
    detail.selectItens = detail.selectItens.filter(id => this.rightList.every(item => item.id !== id));
    this.leftList = [...detail.dataSource];
    this.selectedLeftList = [...detail.selectItens];
    this.transferToRight(detail === null || detail === void 0 ? void 0 : detail.newIndex);
  }
  async handleChangeRight({ detail }) {
    if (!detail.to.getAttribute('id') || detail.to.getAttribute('id') !== this.LEFT_LIST_ID) {
      this.rightList = [...this.reorderArray(detail.dataSource, detail.selectItens, detail.newIndex)];
      return;
    }
    detail.selectItens = detail.selectItens.filter(id => this.leftList.every(item => item.id !== id));
    this.rightList = [...detail.dataSource];
    this.selectedRightList = [...detail.selectItens];
    this.transferToLeft(detail === null || detail === void 0 ? void 0 : detail.newIndex);
  }
  reorderArray(allItems, itemIdsToMove, insertIndex) {
    const filteredItems = allItems.filter(i => !itemIdsToMove.includes(i.id));
    const itemsToMove = allItems.filter(i => itemIdsToMove.includes(i.id));
    filteredItems.splice(insertIndex, 0, ...itemsToMove);
    return filteredItems;
  }
  enableTransferAllToRight() {
    return this.leftList.length > 0;
  }
  enableTransferAllToLeft() {
    return this.rightList.length > 0;
  }
  enableTransferToRight() {
    return this.selectedLeftList.length > 0;
  }
  enableTransferToLeft() {
    return this.selectedRightList.length > 0;
  }
  enableMoveUp(moveAll) {
    if (this.isFilteringRight)
      return false;
    const selectedIndexes = this.getRightSelectedItemsIndex();
    return this.selectedRightList.length > 0
      && !selectedIndexes.includes(0)
      && (moveAll ? true : isContinuousSequence(selectedIndexes));
  }
  enableMoveDown(moveAll) {
    if (this.isFilteringRight)
      return false;
    const selectedIndexes = this.getRightSelectedItemsIndex();
    const lastIndex = this.rightList.length - 1;
    return this.selectedRightList.length > 0
      && !selectedIndexes.includes(lastIndex)
      && (moveAll ? true : isContinuousSequence(selectedIndexes));
  }
  getRightSelectedItemsIndex() {
    return this.selectedRightList.map(id => this.rightList.findIndex(original => original.id === id));
  }
  transferToRight(insertIndex) {
    const { from, to, selectedFrom, selectedTo } = transferItems(Object.assign(Object.assign({}, this.buildTransferToRightConfig()), { insertIndex: insertIndex !== null && insertIndex !== void 0 ? insertIndex : 0 }));
    //Eh preciso limpar a lista antes de atualiza-la por conta de um bug no ciclo de vida do sortable.js
    this.leftList = [];
    requestAnimationFrame(() => this.leftList = [...from]);
    this.rightList = [...to];
    this.selectedLeftList = [...selectedFrom];
    this.selectedRightList = [...selectedTo];
  }
  transferToLeft(insertIndex) {
    const { from, to, selectedFrom, selectedTo } = transferItems(Object.assign(Object.assign({}, this.buildTransferToLeftConfig()), { insertIndex: insertIndex !== null && insertIndex !== void 0 ? insertIndex : 0 }));
    //Eh preciso limpar a lista antes de atualiza-la por conta de um bug no ciclo de vida do sortable.js
    this.rightList = [];
    requestAnimationFrame(() => this.rightList = [...from]);
    this.leftList = [...to];
    this.selectedRightList = [...selectedFrom];
    this.selectedLeftList = [...selectedTo];
  }
  async handleTransferAllToRight() {
    const { from, to, selectedFrom, selectedTo } = transferAll(this.buildTransferToRightConfig());
    this.leftList = [...from];
    this.rightList = [...to];
    this.selectedLeftList = [...selectedFrom];
    this.selectedRightList = [...selectedTo];
    requestAnimationFrame(async () => {
      await this.clearSelectionAll();
    });
  }
  async handleTransferAllToLeft() {
    const { from, to, selectedFrom, selectedTo } = transferAll(this.buildTransferToLeftConfig());
    this.rightList = [...from];
    this.leftList = [...to];
    this.selectedRightList = [...selectedFrom];
    this.selectedLeftList = [...selectedTo];
    requestAnimationFrame(async () => {
      await this.clearSelectionAll();
    });
  }
  buildTransferToRightConfig() {
    return {
      from: this.leftList,
      to: this.rightList,
      selectedFrom: this.selectedLeftList,
      selectedTo: this.selectedRightList,
    };
  }
  buildTransferToLeftConfig() {
    return {
      from: this.rightList,
      to: this.leftList,
      selectedFrom: this.selectedRightList,
      selectedTo: this.selectedLeftList,
    };
  }
  handleMoveUp() {
    this.rightList = [...moveItems(this.selectedRightList, this.rightList, false)];
  }
  handleMoveDown() {
    this.rightList = [...moveItems(this.selectedRightList, this.rightList, true)];
  }
  handleMoveToTop() {
    const { itemsToKeep, itemsToMove } = this.getItemsToKeepAndToMove();
    this.rightList = [...itemsToMove, ...itemsToKeep];
  }
  handleMoveToBottom() {
    const { itemsToKeep, itemsToMove } = this.getItemsToKeepAndToMove();
    this.rightList = [...itemsToKeep, ...itemsToMove];
  }
  handleSelectLeftItem({ detail }) {
    this.selectedLeftList = [...detail.map(({ id }) => id)];
  }
  handleSelectRightItem({ detail }) {
    this.selectedRightList = [...detail.map(({ id }) => id)];
  }
  getItemsToKeepAndToMove() {
    const itemsToKeep = this.rightList.filter(item => !this.selectedRightList.includes(item.id));
    const itemsToMove = this.rightList.filter(item => this.selectedRightList.includes(item.id));
    return { itemsToKeep, itemsToMove };
  }
  async handleTransferToRight() {
    this.transferToRight();
    this.leftFilteredList = [];
    await this.leftEzListInstance.clearSelection();
  }
  async handleTransferToLeft() {
    this.transferToLeft();
    this.rightFilteredList = [];
    await this.rightEzListInstance.clearSelection();
  }
  async clearSelectionAll() {
    await this.rightEzListInstance.clearSelection();
    await this.leftEzListInstance.clearSelection();
  }
  handleChooseLeft() {
    requestAnimationFrame(async () => {
      await this.rightEzListInstance.clearSelection();
    });
  }
  handleChooseRight() {
    if (this.useOnlyRightList)
      return;
    requestAnimationFrame(async () => {
      await this.leftEzListInstance.clearSelection();
    });
  }
  renderList(props) {
    const { idSortableList, list, isFiltering, filteredList, emptyMessage, slotConfig, callbacks, title } = props;
    return (h("ez-sortable-list", { ref: callbacks === null || callbacks === void 0 ? void 0 : callbacks.setRef, title: title, idSortableList: idSortableList, emptyMessage: emptyMessage, class: "ez-size-height--full", dataSource: isFiltering ? filteredList : list, hoverFeedback: true, enableMultipleSelection: true, removeItensMoved: true, entityLabel: this.entityLabel, entityLabelPlural: this.entityLabelPlural, itemRightSlotBuilder: slotConfig === null || slotConfig === void 0 ? void 0 : slotConfig.itemRightSlotBuilder, itemLeftSlotBuilder: slotConfig === null || slotConfig === void 0 ? void 0 : slotConfig.itemLeftSlotBuilder, onItemsReordered: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onChange.bind(this), onEzSelectItens: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onSelect.bind(this), onEzDoubleClick: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onDoubleClick.bind(this), onEzChoose: callbacks === null || callbacks === void 0 ? void 0 : callbacks.onChoose.bind(this) }));
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    return (h(Host, null, !this.useOnlyRightList &&
      h("div", { class: "list__container" }, this.leftList && this.renderList({
        idSortableList: this.LEFT_LIST_ID,
        list: this.leftList,
        title: this.leftTitle,
        isFiltering: this.isFilteringLeft,
        filteredList: this.leftFilteredList,
        emptyMessage: !!((_a = this.emptyMessage) === null || _a === void 0 ? void 0 : _a.LEFT_LIST)
          ? this.emptyMessage.LEFT_LIST
          : this.i18n("ez-double-list.noItemsAvailable", { entity: this.entityLabel }),
        slotConfig: {
          itemRightSlotBuilder: (_c = (_b = this.slotsListBuilder) === null || _b === void 0 ? void 0 : _b.LEFT_LIST) === null || _c === void 0 ? void 0 : _c.itemRightSlotBuilder,
          itemLeftSlotBuilder: (_e = (_d = this.slotsListBuilder) === null || _d === void 0 ? void 0 : _d.LEFT_LIST) === null || _e === void 0 ? void 0 : _e.itemLeftSlotBuilder,
        },
        callbacks: {
          setRef: (ref) => this.leftEzListInstance = ref,
          onChange: (evt) => this.handleChangeLeft(evt),
          onSelect: this.handleSelectLeftItem.bind(this),
          onDoubleClick: this.handleTransferToRight.bind(this),
          onChoose: this.handleChooseLeft.bind(this),
        },
      })), !this.useOnlyRightList &&
      h("div", { class: 'actions__column' }, h("ez-button", { mode: "icon", iconName: "dual-chevron-right", enabled: this.enableTransferAllToRight(), title: this.i18n("ez-double-list.moveAllTo", { list: this.rightListLabel }), size: "small", onClick: this.handleTransferAllToRight.bind(this) }), h("ez-button", { mode: "icon", iconName: "chevron-right", enabled: this.enableTransferToRight(), title: this.i18n("ez-double-list.moveTo", { list: this.rightListLabel }), size: "small", onClick: this.handleTransferToRight.bind(this) }), h("ez-button", { mode: "icon", iconName: "chevron-left", enabled: this.enableTransferToLeft(), title: this.i18n("ez-double-list.moveTo", { list: this.leftListLabel }), size: "small", onClick: this.handleTransferToLeft.bind(this) }), h("ez-button", { mode: "icon", iconName: "dual-chevron-left", enabled: this.enableTransferAllToLeft(), title: this.i18n("ez-double-list.moveAllTo", { list: this.leftListLabel }), size: "small", onClick: this.handleTransferAllToLeft.bind(this) })), h("div", { class: "list__container" }, this.rightList && this.renderList({
      idSortableList: this.RIGHT_LIST_ID,
      list: this.rightList,
      title: this.rightTitle,
      isFiltering: this.isFilteringRight,
      filteredList: this.rightFilteredList,
      emptyMessage: !!((_f = this.emptyMessage) === null || _f === void 0 ? void 0 : _f.RIGHT_LIST)
        ? this.emptyMessage.RIGHT_LIST
        : this.i18n("ez-double-list.noItemsSelected", { entity: this.entityLabel }),
      slotConfig: {
        itemRightSlotBuilder: (_h = (_g = this.slotsListBuilder) === null || _g === void 0 ? void 0 : _g.RIGHT_LIST) === null || _h === void 0 ? void 0 : _h.itemRightSlotBuilder,
        itemLeftSlotBuilder: (_k = (_j = this.slotsListBuilder) === null || _j === void 0 ? void 0 : _j.RIGHT_LIST) === null || _k === void 0 ? void 0 : _k.itemLeftSlotBuilder,
      },
      callbacks: {
        setRef: (ref) => this.rightEzListInstance = ref,
        onChange: (evt) => this.handleChangeRight(evt),
        onSelect: this.handleSelectRightItem.bind(this),
        onDoubleClick: this.handleTransferToLeft.bind(this),
        onChoose: this.handleChooseRight.bind(this),
      },
    })), h("div", { class: 'actions__column' }, h("ez-button", { mode: "icon", iconName: "dual-chevron-up", enabled: this.enableMoveUp(true), title: this.i18n("ez-double-list.moveToFirstPosition"), size: "small", onClick: this.handleMoveToTop.bind(this) }), h("ez-button", { mode: "icon", iconName: "chevron-up", enabled: this.enableMoveUp(), title: this.i18n("ez-double-list.moveUp"), size: "small", onClick: this.handleMoveUp.bind(this) }), h("ez-button", { mode: "icon", iconName: "chevron-down", enabled: this.enableMoveDown(), title: this.i18n("ez-double-list.moveDown"), size: "small", onClick: this.handleMoveDown.bind(this) }), h("ez-button", { mode: "icon", iconName: "dual-chevron-down", enabled: this.enableMoveDown(true), title: this.i18n("ez-double-list.moveToLastPosition"), size: "small", onClick: this.handleMoveToBottom.bind(this) }))));
  }
  static get watchers() { return {
    "leftList": ["observeLeftList"],
    "rightList": ["observeRightList"]
  }; }
};
EzDoubleList.style = ezDoubleListCss;

export { EzDoubleList as ez_double_list };
