import { h, Host } from '@stencil/core';
import { moveItems, transferAll, transferItems } from './doubleListHelper';
import { ObjectUtils } from '@sankhyalabs/core';
import { isContinuousSequence } from '../ez-list/ezListHelper';
import initI18n from '../../utils/i18n';
export class EzDoubleList {
  constructor() {
    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 is() { return "ez-double-list"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-double-list.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-double-list.css"]
    };
  }
  static get properties() {
    return {
      "leftList": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "ListItem[]",
          "resolved": "ListItem[]",
          "references": {
            "ListItem": {
              "location": "import",
              "path": "../ez-sortable-list/ez-sortable-list"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a lista origem."
        },
        "defaultValue": "[]"
      },
      "leftTitle": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o t\u00EDtulo da lista origem."
        },
        "attribute": "left-title",
        "reflect": false
      },
      "rightList": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "ListItem[]",
          "resolved": "ListItem[]",
          "references": {
            "ListItem": {
              "location": "import",
              "path": "../ez-sortable-list/ez-sortable-list"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a lista destino."
        },
        "defaultValue": "[]"
      },
      "entityLabel": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Nome da entidade listada.\nExemplo: \"Campo\", \"Item\", \"Empresa\"."
        },
        "attribute": "entity-label",
        "reflect": false,
        "defaultValue": "'item'"
      },
      "entityLabelPlural": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Varia\u00E7\u00E3o plural do nome da entidade listada.\nExemplo: \"Campos\", \"Itens\", \"Empresas\"."
        },
        "attribute": "entity-label-plural",
        "reflect": false,
        "defaultValue": "'itens'"
      },
      "leftListLabel": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "R\u00F3tulo da lista esquerda."
        },
        "attribute": "left-list-label",
        "reflect": false,
        "defaultValue": "'dispon\u00EDveis'"
      },
      "rightListLabel": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "R\u00F3tulo da lista direita."
        },
        "attribute": "right-list-label",
        "reflect": false,
        "defaultValue": "'selecionados'"
      },
      "useOnlyRightList": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se ir\u00E1 exibir apenas a lista da direita."
        },
        "attribute": "use-only-right-list",
        "reflect": false,
        "defaultValue": "false"
      },
      "rightTitle": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o t\u00EDtulo da lista destino."
        },
        "attribute": "right-title",
        "reflect": false
      },
      "emptyMessage": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "EmptyMessage",
          "resolved": "EmptyMessage",
          "references": {
            "EmptyMessage": {
              "location": "local"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Objeto que define as mensagens a serem exibidas quando a lista est\u00E1 vazia\nExemplo:\n{\nLEFT_LIST?: \"Lista lado esquerdo vazia.\",\nRIGHT_LIST?: \"Lista lado direito vazia.\";\n}"
        }
      },
      "slotsListBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "DoubleListSlots",
          "resolved": "DoubleListSlots",
          "references": {
            "DoubleListSlots": {
              "location": "local"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Objeto que define os m\u00E9todos de constru\u00E7\u00E3o dos elementos visuais para os itens de cada lista.\n\nEste objeto permite configurar dinamicamente os elementos HTML que ser\u00E3o exibidos ao lado\nesquerdo e direito dos itens em ambas as listas (`LEFT_LIST` e `RIGHT_LIST`)."
        }
      }
    };
  }
  static get states() {
    return {
      "leftFilteredList": {},
      "rightFilteredList": {},
      "selectedLeftList": {},
      "selectedRightList": {},
      "isFilteringLeft": {},
      "isFilteringRight": {}
    };
  }
  static get events() {
    return [{
        "method": "ezLeftListChanged",
        "name": "ezLeftListChanged",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido ao realizar uma altera\u00E7\u00E3o na lista esquerda do componente."
        },
        "complexType": {
          "original": "Array<ListItem>",
          "resolved": "ListItem[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "ListItem": {
              "location": "import",
              "path": "../ez-sortable-list/ez-sortable-list"
            }
          }
        }
      }, {
        "method": "ezRightListChanged",
        "name": "ezRightListChanged",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido ao realizar uma altera\u00E7\u00E3o na lista direita do componente."
        },
        "complexType": {
          "original": "Array<ListItem>",
          "resolved": "ListItem[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "ListItem": {
              "location": "import",
              "path": "../ez-sortable-list/ez-sortable-list"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "resetSelectedLists": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "leftList",
        "methodName": "observeLeftList"
      }, {
        "propName": "rightList",
        "methodName": "observeRightList"
      }];
  }
}
