'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-a7b0c73d.js');
const index$1 = require('./index-1be40f19.js');
const core = require('@sankhyalabs/core');

const ezMultiSelectionListCss = ".sc-ez-multi-selection-list-h{--ez-check--outter-gap:0px;--ez-multi-selection-default-height:322px;display:block;width:304px;height:var(--ez-multi-selection-default-height);min-height:fit-content;max-height:calc(100vh - 350px)}.multi-selection__input.sc-ez-multi-selection-list{margin-bottom:var(--space--2xs, 8px)}.multi-selection__content-options.sc-ez-multi-selection-list{position:relative;left:-4px}.multi-selection__select-all.sc-ez-multi-selection-list{height:var(--space--xl);margin:0 var(--space--small, 6px)}.multi-selection__list.sc-ez-multi-selection-list{max-height:calc(100vh - 435px);overflow-y:auto;overflow-x:clip}.multi-selection__list.sc-ez-multi-selection-list::-webkit-scrollbar{width:var(--space--small);min-width:var(--space--small);max-width:var(--space--small)}";

var ViewScenarios;
(function (ViewScenarios) {
  ViewScenarios["DATASOURCE_RESULTS"] = "DATASOURCE_RESULTS";
  ViewScenarios["DATASOURCE_RESULTS_EMPTY"] = "DATASOURCE_RESULTS_EMPTY";
  ViewScenarios["DATASOURCE_INIT"] = "DATASOURCE_INIT";
  ViewScenarios["OPTIONS_EMPTY"] = "OPTIONS_EMPTY";
  ViewScenarios["OPTIONS"] = "OPTIONS";
})(ViewScenarios || (ViewScenarios = {}));
const EzMuiltiSelectionList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.changeFilteredOptions = index.createEvent(this, "changeFilteredOptions", 7);
    this.columnName = undefined;
    this.dataSource = undefined;
    this.useOptions = false;
    this.options = undefined;
    this.isTextSearch = false;
    this.filteredOptions = undefined;
    this.displayOptions = undefined;
    this.viewScenario = undefined;
    this.displayOptionToCheckAllItems = true;
  }
  async componentWillLoad() {
    this.i18n = await index$1.initI18n();
  }
  async clearFilteredOptions() {
    this.setInitialScenario();
    this.filteredOptions = [];
    if (this.searchInput) {
      await this.searchInput.clearValue();
    }
    if (this.filterInput) {
      this.filterInput.value = '';
    }
  }
  onChangeUseOptions() {
    this.setInitialScenario();
  }
  onChangeOptions() {
    if (this.options) {
      this.filteredOptions = this.ordenationByCheckStateAndAlphabetically(this.options);
    }
    this.checkInput && this.changeCheckAllValeuFromFilteredOptions();
    this.setInitialScenario();
  }
  onChangeFilteredOptions(optionsListUpdated) {
    this.displayOptions = this.filteredOptions;
    this.displayOptionToCheckAllItems = this.filteredOptions.length > 1;
    this.checkInput && this.changeCheckAllValeuFromFilteredOptions();
    this.changeFilteredOptions.emit(optionsListUpdated);
  }
  componentDidLoad() {
    this.onChangeOptions();
  }
  componentDidRender() {
    this.changeCheckAllValeuFromFilteredOptions();
  }
  ordenationByCheckStateAndAlphabetically(filteredOptions) {
    const listWithSelectChecked = [];
    const listWithNotSelectChecked = [];
    let emptyElement;
    filteredOptions.forEach(item => {
      if (item.value == undefined || item.label === "") {
        emptyElement = Object.assign(Object.assign({}, item), { label: this.i18n("ez-multi-selection-list.empty") });
      }
      else {
        (item.check ? listWithSelectChecked.push(item) : listWithNotSelectChecked.push(item));
      }
    });
    return (emptyElement == undefined ? [] : [emptyElement])
      .concat(this.dataSource == undefined ? core.ArrayUtils.sortAlphabetically(listWithSelectChecked) : this.dataSource.sortItems(this.columnName, listWithSelectChecked))
      .concat(this.dataSource == undefined ? core.ArrayUtils.sortAlphabetically(listWithNotSelectChecked) : this.dataSource.sortItems(this.columnName, listWithNotSelectChecked));
  }
  changeCheckAllValeuFromFilteredOptions() {
    var _a, _b, _c, _d;
    const selectAll = (_a = this.filteredOptions) === null || _a === void 0 ? void 0 : _a.every(item => item.check === true);
    const notSelectAll = (_b = this.filteredOptions) === null || _b === void 0 ? void 0 : _b.every(item => item.check === false);
    const selectIndeterminated = ((_c = this.filteredOptions) === null || _c === void 0 ? void 0 : _c.some(item => item.check === false)) && ((_d = this.filteredOptions) === null || _d === void 0 ? void 0 : _d.some(item => item.check === true)) && (!selectAll || !notSelectAll);
    if (this.checkInput && selectAll) {
      this.checkInput.indeterminate = false;
      this.checkInput.value = true;
      return;
    }
    if (this.checkInput && selectIndeterminated) {
      this.checkInput.indeterminate = true;
      this.checkInput.value = false;
      return;
    }
    if (this.checkInput && notSelectAll) {
      this.checkInput.indeterminate = false;
      this.checkInput.value = false;
      return;
    }
  }
  setInitialScenario() {
    if (this.useOptions) {
      this.viewScenario = ViewScenarios.OPTIONS;
      this.changeCheckAllValeuFromFilteredOptions();
      return;
    }
    this.viewScenario = this.options && this.options.length > 0 ? ViewScenarios.DATASOURCE_RESULTS : ViewScenarios.DATASOURCE_INIT;
  }
  async searchWithDataSource(searchArgument, fieldName) {
    const { argument, mode } = searchArgument;
    if (mode !== 'PRELOAD' && fieldName) {
      return this.dataSource.fetchData(argument, fieldName);
    }
  }
  async handleSearchOnDataSource(event) {
    var _a;
    const optionsToSort = (_a = this.filteredOptions) !== null && _a !== void 0 ? _a : [];
    if (event.detail && !optionsToSort.some(item => item.value == event.detail.value)) {
      this.filteredOptions = this.ordenationByCheckStateAndAlphabetically([...optionsToSort, event.detail]);
    }
    this.viewScenario = ViewScenarios.DATASOURCE_RESULTS;
    await this.searchInput.clearValue();
  }
  async handleRemoveItemFromOptions(item) {
    this.filteredOptions = this.ordenationByCheckStateAndAlphabetically(this.filteredOptions.filter(i => i.value !== item.value));
    if (this.filteredOptions.length === 0) {
      this.viewScenario = ViewScenarios.DATASOURCE_INIT;
    }
    if (this.searchInput) {
      await this.searchInput.clearValue();
    }
  }
  handleSearchOnOption(event) {
    if (event.detail) {
      this.displayOptions = core.ArrayUtils.applyStringFilter(event.detail, this.filteredOptions, true);
      this.viewScenario = this.displayOptions.length === 0 ? ViewScenarios.OPTIONS_EMPTY : ViewScenarios.OPTIONS;
      return;
    }
    this.displayOptions = this.filteredOptions;
    this.viewScenario = ViewScenarios.OPTIONS;
  }
  handleChangeSelectAllItems(event) {
    this.filteredOptions = this.ordenationByCheckStateAndAlphabetically([
      ...this.filteredOptions.map(item => {
        item.check = !!event.detail;
        return item;
      }),
    ]);
  }
  handleChangeSelectedItem(event) {
    const { detail: itemCheckSelected } = event;
    const itemSelected = this.filteredOptions.find(item => item.label === itemCheckSelected.label);
    itemSelected.check = itemCheckSelected.check;
    this.changeFilteredOptions.emit(this.filteredOptions);
  }
  buildViewList(hasDelete) {
    return (index.h(index.Fragment, null, this.displayOptionToCheckAllItems && (index.h("ez-check", { ref: (element) => (this.checkInput = element), label: this.i18n("ez-multi-selection-list.selectAll"), class: "multi-selection__select-all", onEzChange: this.handleChangeSelectAllItems.bind(this) })), index.h("ez-list", { class: "multi-selection__list", dataSource: this.displayOptions.map(opt => (Object.assign(Object.assign({}, opt), { id: opt.value }))), listMode: "check", hoverFeedback: true, onEzCheckChange: this.handleChangeSelectedItem.bind(this), itemSlotBuilder: hasDelete ? this.buildDeleteIconSlot.bind(this) : null })));
  }
  buildDeleteIconSlot(item) {
    return index.h("ez-icon", { style: { cursor: 'pointer' }, iconName: "delete", onClick: () => this.handleRemoveItemFromOptions(item) });
  }
  buildInitViewWithDataSource() {
    return index.h("multi-selection-box-message", { message: this.i18n("ez-multi-selection-list.initMessage") });
  }
  buildViewEmptyResults() {
    return index.h("multi-selection-box-message", { message: this.i18n("ez-multi-selection-list.emptyResults") });
  }
  scenarioToDisplay(view) {
    const scenarios = {
      [ViewScenarios.DATASOURCE_INIT]: () => this.buildInitViewWithDataSource(),
      [ViewScenarios.DATASOURCE_RESULTS]: () => this.buildViewList(true),
      [ViewScenarios.DATASOURCE_RESULTS_EMPTY]: () => this.buildViewEmptyResults(),
      [ViewScenarios.OPTIONS_EMPTY]: () => this.buildViewEmptyResults(),
      [ViewScenarios.OPTIONS]: () => this.buildViewList(false),
    };
    const scenarioBuilder = scenarios[view];
    return scenarioBuilder ? scenarioBuilder() : undefined;
  }
  render() {
    return (index.h(index.Host, null, index.h("div", { class: "multi-selection" }, this.useOptions ? (index.h("ez-filter-input", { ref: (element) => (this.filterInput = element), label: this.i18n("ez-multi-selection-list.search"), onEzChange: this.handleSearchOnOption.bind(this) })) : (index.h("ez-search", { class: "multi-selection__input", label: this.i18n("ez-multi-selection-list.search"), ref: (element) => (this.searchInput = element), suppressEmptyOption: true, showOptionValue: false, showSelectedValue: false, optionLoader: (search) => this.searchWithDataSource(search, this.columnName), onEzChange: this.handleSearchOnDataSource.bind(this), isTextSearch: this.isTextSearch })), index.h("ez-scroll", { class: "multi-selection__content-options" }, this.scenarioToDisplay(this.viewScenario)))));
  }
  static get watchers() { return {
    "useOptions": ["onChangeUseOptions"],
    "options": ["onChangeOptions"],
    "filteredOptions": ["onChangeFilteredOptions"]
  }; }
};
EzMuiltiSelectionList.style = ezMultiSelectionListCss;

exports.ez_multi_selection_list = EzMuiltiSelectionList;
