import { h, r as registerInstance, c as createEvent, f as forceUpdate, H as Host, g as getElement } from './index-baa5e267.js';
import { ElementIDUtils, StringUtils, ObjectUtils } from '@sankhyalabs/core';
import { i as initI18n } from './index-41363fa6.js';

const ICON_EXPANDED = "chevron-down";
const ICON_COLAPSED = "chevron-right";
const defaultIconResolver = (item, expanded, _level) => {
  if (expanded) {
    return item.iconExpanded || ICON_EXPANDED;
  }
  return item.iconContracted || ICON_COLAPSED;
};

const defaultTooltipResolver = (item, _enabled, _level) => {
  return item.tooltip || item.label;
};

const TreeItem = (props) => {
  const { node, selectedId, itemClick, iconClick, iconResolver, tooltipResolver, itemsList, itemDoubleClick } = props;
  if (!node.visible) {
    return;
  }
  const treeItem = node.item;
  const level = props.level || 1;
  const disabled = node.isDisabled();
  const expanded = !disabled && treeItem.expanded;
  const expandable = node.isExpandable();
  const available = !disabled && !node.isPlaceHolder;
  if (available) {
    itemsList.push(treeItem);
  }
  function handleIconClick(event) {
    event.stopPropagation();
    if (available) {
      iconClick(treeItem);
    }
  }
  function handleIconDoubleClick(event) {
    event.stopPropagation();
  }
  return (h("ul", { class: level === 1 ? "first-level" : undefined },
    h("li", Object.assign({ title: tooltipResolver(treeItem, !disabled, level), class: `tree-item ${treeItem.id !== selectedId ? "tree-item-error" : ""}`, onClick: () => available && itemClick(treeItem), onDblClick: () => available && itemDoubleClick(treeItem) }, {
      disabled,
      selected: treeItem.id === selectedId,
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(`ezTreeItem_${treeItem.id}`)
    }),
      h("div", { class: "item-label-container" },
        h("div", { class: "item-icon-box" }, expandable &&
          h("ez-icon", { id: treeItem.id, class: "item-icon", size: "small", iconName: iconResolver(treeItem, expanded, level), onClick: (event) => handleIconClick(event), onDblClick: (event) => handleIconDoubleClick(event) })),
        h("label", { class: `item-label ${treeItem.bold ? "item-label--bold" : ""}` }, treeItem.label)),
      getBadgeElement(treeItem.id, treeItem.badge, treeItem.id === selectedId)),
    expanded
      && node.getChildren().map(child => h(TreeItem, { selectedId: selectedId, node: child, itemClick: itemClick, iconClick: iconClick, level: level + 1, iconResolver: iconResolver, tooltipResolver: tooltipResolver, itemsList: itemsList, itemDoubleClick: itemDoubleClick }))));
};
function getBadgeElement(itemId, badge, isSelectedItem) {
  if (badge == undefined) {
    return;
  }
  if (typeof badge === "string") {
    return h("div", { class: `tree-item-badge ${isSelectedItem ? null : badge}` }, badge === "error" &&
      h("ez-icon", { id: `${itemId}-badge-error`, class: "tree-item-badge-error-icon", size: "x-small", style: { color: 'white' }, iconName: "alert-circle" }));
  }
  if (badge.type === "text") {
    return h("div", { id: `${itemId}-badge-text`, class: "tree-item-badge-text" }, badge.text);
  }
  return h("div", null,
    h("ez-icon", { id: `${itemId}-badge-icon`, class: "tree-item-badge-icon", style: { "--ez-icon--color": `var(--ez-tree__badge--icon-color--${badge.iconColor || "default"})` }, iconName: badge.iconName }));
}

class Node {
  constructor(tree, item, parent, isPlaceHolder = false) {
    this.children = new Map();
    this.visible = true;
    this.item = item;
    this.parent = parent;
    this._tree = tree;
    this.isPlaceHolder = isPlaceHolder;
    if (item && !isPlaceHolder) {
      this._isLazyLoad = typeof item.children === "function" || item.childrenCount > 0;
      if (Array.isArray(item.children)) {
        Array.from(item.children).forEach(item => this.addChild(this._tree, item));
        this._childrenLoaded = true;
      }
    }
    else {
      this._isLazyLoad = false;
      this._childrenLoaded = true;
    }
  }
  refresh(newItem) {
    if (this.isPlaceHolder) {
      return;
    }
    this.item = Object.assign({}, newItem);
    this._isLazyLoad = typeof this.item.children === "function" || this.item.childrenCount > 0;
    const oldChildren = this.children;
    this.children = new Map();
    if (Array.isArray(this.item.children)) {
      if (this.item.expanded === undefined) {
        this.item.expanded = true;
      }
      Array.from(this.item.children).forEach(item => {
        const node = oldChildren.get(item.id);
        if (node) {
          if (item.expanded === undefined) {
            item.expanded = node.item.expanded;
          }
          node.refresh(item);
          this.children.set(item.id, node);
        }
        else {
          if (item.expanded === undefined) {
            item.expanded = true;
          }
          this.addChild(this._tree, Object.assign({}, item));
        }
      });
      this._childrenLoaded = true;
    }
    else {
      this._childrenLoaded = false;
    }
  }
  isDisabled() {
    if (this.isPlaceHolder) {
      return false;
    }
    return this._tree.isNodeDisabled(this.item.id, this.item.disabled);
  }
  updateChildren(children) {
    if (this.isPlaceHolder) {
      return;
    }
    this.refresh(Object.assign(Object.assign({}, this.item), { children }));
  }
  addChild(tree, item) {
    if (!this.children.has(item.id)) {
      this.children.set(item.id, new Node(tree, item, this));
    }
  }
  removeChild(id) {
    if (this.children.has(id)) {
      this.children.delete(id);
      return true;
    }
    return false;
  }
  addPlaceHolder() {
    this.children.clear();
    const id = this.item.id;
    this.children.set(id, new Node(undefined, { id: `placeholder_${id}`, label: "Carregando..." }, this, true));
  }
  getNode(id) {
    if (this.children.has(id)) {
      return this.children.get(id);
    }
    const childrenArray = Array.from(this.children.values());
    for (const child of childrenArray) {
      const result = child.getNode(id);
      if (result) {
        return result;
      }
    }
  }
  needLoad() {
    return this._isLazyLoad && !this._childrenLoaded;
  }
  isExpandable() {
    if (this._isLazyLoad) {
      return true;
    }
    if (this.children.size > 0) {
      return true;
    }
    return false;
  }
  getChildren() {
    if (this.isPlaceHolder) {
      return [];
    }
    if (this.needLoad()) {
      this._tree.loadChildren(this);
    }
    return Array.from(this.children.values());
  }
}

class Tree extends Node {
  constructor(changeCallback) {
    super(undefined);
    this._disabledValues = new Map();
    this._changeCallback = changeCallback;
  }
  async addChildAt(parentId, item) {
    const parent = this.getNode(parentId);
    if (parent == undefined) {
      this.addChild(this, item);
      this._changeCallback();
      return;
    }
    parent.addChild(this, item);
    this._changeCallback();
  }
  setDisabled(id, value) {
    this._disabledValues.set(id, value);
    this._changeCallback();
  }
  isNodeDisabled(id, defaultValue) {
    if (!this._disabledValues.has(id)) {
      return defaultValue;
    }
    return this._disabledValues.get(id);
  }
  load(items) {
    if (items === this._currentItems) {
      return;
    }
    this._currentItems = items;
    const oldChildren = this.children;
    this.children = new Map();
    this._disabledValues.clear();
    items.forEach(item => {
      const node = oldChildren.get(item.id);
      if (node) {
        node.refresh(item);
        this.children.set(item.id, node);
      }
      else {
        this.addChild(this, Object.assign({}, item));
      }
    });
  }
  async setFilterPattern(pattern, enableHierarchicalFilter = true) {
    if (pattern && enableHierarchicalFilter && pattern.includes('.')) {
      const layers = pattern.split('.').map(p => StringUtils.replaceAccentuatedCharsKeepSymbols(p.trim()));
      await this.applyLayeredFilter(this, layers, 0);
    }
    else {
      this._filterPattern = StringUtils.replaceAccentuatedCharsKeepSymbols(pattern);
      this.setAllChildrenExpanded(this, false);
      this.applyFilter(this);
    }
    this._changeCallback();
  }
  updateItem(item) {
    if (item == undefined) {
      return;
    }
    const node = this.getNode(item.id);
    if (node == undefined) {
      return;
    }
    Object.keys(item).forEach(attrib => node.item[attrib] = item[attrib]);
    if (item.children == undefined) {
      node.children.clear();
    }
    else if (Array.isArray(item.children)) {
      node.updateChildren(item.children);
    }
    this._changeCallback();
  }
  removeItem(id) {
    if (!id) {
      return;
    }
    const node = this.getNode(id);
    if (!node) {
      return;
    }
    if (node.parent) {
      node.parent.removeChild(id);
    }
    else {
      this.children.delete(id);
    }
    this._disabledValues.delete(id);
    this._changeCallback();
  }
  async open(path) {
    return new Promise(async (resolve) => {
      await this.walkPath(this, path, node => node.item.expanded = true);
      resolve();
    });
  }
  setAllChildrenVisible(node) {
    node.children.forEach(child => {
      child.visible = true;
      this.setAllChildrenVisible(child);
    });
  }
  applyFilter(node) {
    if (!this._filterPattern) {
      node.visible = true;
      this.setAllChildrenVisible(node);
      return;
    }
    node.children.forEach((value) => {
      this.applyFilter(value);
    });
    if (node.item == undefined) {
      return;
    }
    const normalizedLabel = StringUtils.replaceAccentuatedCharsKeepSymbols(node.item.label);
    let isVisible = false;
    if (normalizedLabel.includes(this._filterPattern)) {
      isVisible = true;
      node.item.expanded = true;
      this.setAllChildrenVisible(node);
    }
    else {
      const childrenArray = Array.from(node.children.values());
      for (let i = 0; i < childrenArray.length; i++) {
        if (childrenArray[i].visible) {
          isVisible = true;
          node.item.expanded = true;
          break;
        }
      }
    }
    node.visible = isVisible;
  }
  async applyLayeredFilter(node, layers, level) {
    if (!node.item) {
      const results = await Promise.all(Array.from(node.children.values()).map(child => this.applyLayeredFilter(child, layers, level)));
      const childFound = results.some(Boolean);
      node.visible = childFound;
      return childFound;
    }
    const normalizedLabel = StringUtils.replaceAccentuatedCharsKeepSymbols(node.item.label);
    if (!normalizedLabel.includes(layers[level])) {
      const results = await Promise.all(Array.from(node.children.values()).map(child => this.applyLayeredFilter(child, layers, level)));
      const childFound = results.some(Boolean);
      if (childFound)
        node.item.expanded = true;
      node.visible = childFound;
      return childFound;
    }
    if (level === layers.length - 1) {
      node.visible = true;
      this.setAllChildrenVisible(node);
      return true;
    }
    const results = await Promise.all(Array.from(node.children.values()).map(child => this.applyLayeredFilter(child, layers, level + 1)));
    const childFound = results.some(Boolean);
    if (childFound)
      node.item.expanded = true;
    node.visible = childFound;
    return childFound;
  }
  async walkPath(parent, path, callback, currentLevel = 0) {
    return new Promise(async (resolve) => {
      const levels = path.split(">>").map(item => item.trim());
      if (levels.length > currentLevel) {
        const node = parent.getNode(levels[currentLevel]);
        if (node) {
          if (node.needLoad()) {
            await this.loadLevel(node);
          }
          callback(node);
          await this.walkPath(node, path, callback, currentLevel + 1);
        }
      }
      resolve();
    });
  }
  async loadChildren(node) {
    return new Promise(resolve => {
      this.loadLevel(node).then(() => {
        resolve();
        this._changeCallback();
      });
    });
  }
  expandAll() {
    this.setAllChildrenExpanded(this, true);
    this._changeCallback();
  }
  collapseAll() {
    this.setAllChildrenExpanded(this, false);
    this._changeCallback();
  }
  setAllChildrenExpanded(node, expanded) {
    if (node.item && !node.isPlaceHolder) {
      node.item.expanded = expanded;
    }
    node.children.forEach(child => {
      this.setAllChildrenExpanded(child, expanded);
    });
  }
  async loadLevel(node) {
    return new Promise(resolve => {
      node.addPlaceHolder();
      const loader = node.item.children;
      loader(node.item).then(result => {
        node.updateChildren(result);
        resolve();
      });
    });
  }
}

const ezTreeCss = ":host{--ez-tree--border-radius:var(--border--radius-small, 8px);--ez-tree--padding-inline-start:20px;--ez-tree--margin:var(--space--extra-small, 3px);--ez-tree--margin-right:0px;--ez-tree--user-select:auto;--ez-tree--font-family:var(--font-pattern, Arial);--ez-tree--font-size:var(--text--medium, 14px);--ez-tree--selected--font-weight:var(--text-weight--large, 600);--ez-tree--font-weight:var(--text-weight--small, 400);--ez-tree--color:var(--title--primary, #2B3A54);--ez-tree--selected--color:var(--color--primary, #008561);--ez-tree--disabled--color:var(--text--disable, #AFB6C0);--ez-tree--font-weight--bold:var(--text-weight--large, 600);--ez-tree__tree-item--height:var(--size-medium, 18px);--ez-tree__tree-item--padding:var(--space--small, 6px);--ez-tree__tree-item--background-color:var(--background--xlight, #FFFFFF);--ez-tree__tree-item--selected--background-color:var(--color--primary-300, #E2F4EF);--ez-tree__tree-item--hover--background-color:var(--background--medium, #F0F3F7);--ez-tree__tree-item--disabled--background-color:var(--ez-tree__tree-Item--background-color);--ez-tree__item-icon-box--height:var(--ez-tree__tree-item--height);--ez-tree__item-icon-box--width:var(--size-medium, 18px);--ez-tree__item-icon-box--padding:var(--ez-tree__tree-item--padding);--ez-tree__badge--icon-color--default:var(--title--primary, #2B3A54);--ez-tree__badge--icon-color--error:var(--color--error, #da4453);--ez-tree__badge--icon-color--success:var(--color-alert--success-800, #157a00);--ez-tree__badge--icon-color--warning:var(--color--warning, #f2d410);--ez-tree__badge--icon-color--disabled:var(--text--disable, #AFB6C0);display:flex;flex-direction:column;margin:0 var(--ez-tree--margin) var(--ez-tree--margin) var(--ez-tree--margin);outline:none}ul{list-style-type:none;margin:0;cursor:default;padding-inline-start:var(--ez-tree--padding-inline-start)}ul.first-level{padding-inline-start:0}.tree-item-badge{width:16px;height:16px;background:transparent;border-radius:50%;transition:all 300ms ease-in-out;display:flex;align-items:center;justify-content:center}.tree-item-badge-error-icon{--ez-icon--color:white}.tree-item-badge-text{font-family:var(--ez-tree--font-family);font-size:var(--ez-tree--font-size);font-weight:var(--ez-tree--font-weight);color:var(--ez-tree--color)}.tree-item-badge.error{background:var(--color--error)}.tree-item-badge.warning{background:var(--color--warning)}.tree-item-badge.success{background:var(--color--success)}.item-label-container{display:flex;align-items:center;overflow:hidden}.tree-item{display:flex;align-items:center;cursor:pointer;margin-top:var(--ez-tree--margin);margin-right:var(--ez-tree--margin-right);border-radius:var(--ez-tree--border-radius);height:var(--ez-tree__tree-item--height);padding:var(--ez-tree__tree-item--padding);justify-content:space-between}.tree-item[selected]{background-color:var(--ez-tree__tree-item--selected--background-color)}.tree-item:hover{background-color:var(--ez-tree__tree-item--hover--background-color)}.tree-item[disabled],.tree-item[disabled]:hover{background-color:var(--ez-tree__tree-item--disabled--background-color)}.item-icon-box{display:flex;align-items:center;justify-content:center;width:var(--ez-tree__item-icon-box--width);height:var(--ez-tree__item-icon-box--height);padding:var(--ez-tree__item-icon-box--padding) var(--ez-tree__item-icon-box--padding) var(--ez-tree__item-icon-box--padding) 0}.item-icon{--ez-icon--color:var(--ez-tree--color)}.item-icon:hover{cursor:pointer}.tree-item[selected] .item-icon{--ez-icon--color:var(--ez-tree--selected--color)}.tree-item[disabled] .item-icon{cursor:unset;--ez-icon--color:var(--ez-tree--disabled--color)}.item-label{cursor:inherit;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;user-select:var(--ez-tree--user-select);font-family:var(--ez-tree--font-family);font-size:var(--ez-tree--font-size);font-weight:var(--ez-tree--font-weight);color:var(--ez-tree--color)}.item-label--bold{font-weight:var(--ez-tree--font-weight--bold)}.tree-item[selected] .item-label{color:var(--ez-tree--selected--color);font-weight:var(--ez-tree--selected--font-weight)}.tree-item[disabled] .item-label{color:var(--ez-tree--disabled--color)}";

const EzTree = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezChange = createEvent(this, "ezChange", 7);
    this.ezOpenItem = createEvent(this, "ezOpenItem", 7);
    this.ezDbClickItem = createEvent(this, "ezDbClickItem", 7);
    this.ezRemoveItem = createEvent(this, "ezRemoveItem", 7);
    this._onItemClick = (item) => {
      if (!this.selectable) {
        this.openClose(item);
        return;
      }
      if (this.value && this.value.id === item.id) {
        this.value = undefined;
        return;
      }
      this.value = item;
    };
    this._onIconClick = (item) => {
      this.openClose(item);
    };
    this._tree = new Tree(() => forceUpdate(this));
    this._waintingForLoad = undefined;
    this.items = [];
    this.value = undefined;
    this.selectedId = undefined;
    this.iconResolver = defaultIconResolver;
    this.tooltipResolver = undefined;
    this.enableHierarchicalFilter = true;
    this.selectable = true;
  }
  /**
   * Efetua a seleção de um item.
   */
  async selectItem(id) {
    const node = this._tree.getNode(id);
    if (node) {
      this.value = node.item;
    }
    else {
      this.value = undefined;
    }
  }
  /**
   * Realiza a abertura de um item, incluindo a hieraquia acima.
   * Observação para carga dinâmica (Lazyload): O item solicitado já deve
   * estar carregado na lista. Nos casos onde o item ainda não esteja
   * carregado o id pode ser uma string no formato "id1>>id2>>id3",
   * tornando possível a carga a partir de um ponto já carregado.
   */
  async openItem(id) {
    this._waintingForLoad = true;
    await this._tree.open(id);
    this._waintingForLoad = false;
  }
  /**
   * Desabilita um ou mais itens.
   */
  async disableItem(id) {
    [].concat(id).forEach(item => this._tree.setDisabled(item, true));
  }
  /**
  * Habilita um ou mais itens.
  */
  async enableItem(id) {
    [].concat(id).forEach(item => this._tree.setDisabled(item, false));
  }
  /**
   * Adiciona um ou mais itens. Opcionalmente pode-se determinar a qual
   * item da árvore será anexado o item. Caso não informado parentId,
   * adiciona no item selecionado.
   * Observação para carga dinâmica (Lazyload): O parentId deve ser
   * um item carregado atualmente na árvore.
   */
  async addChild(item, parentId) {
    var _a;
    if (parentId == undefined) {
      parentId = (_a = this.value) === null || _a === void 0 ? void 0 : _a.id;
    }
    this._tree.addChildAt(parentId, item);
    this.addItemInIndexedList(parentId, item);
    const node = this._tree.getNode(parentId);
    if (node) {
      node.item.expanded = true;
    }
    else {
      this.collapseAll();
    }
  }
  /**
   * Efetua a seleção de um item.
   */
  async applyFilter(pattern) {
    await this._tree.setFilterPattern(pattern, this.enableHierarchicalFilter);
  }
  /**
   * Expande todos os itens da árvore.
   */
  async expandAll() {
    this._tree.expandAll();
  }
  /**
   * Recolhe todos os itens da árvore.
   */
  async collapseAll() {
    this._tree.collapseAll();
  }
  /**
   * Atualiza um item
   */
  async updateItem(item, config) {
    var _a, _b, _c;
    if (Array.isArray(item)) {
      item.forEach(i => this.updateItem(i, config));
      return;
    }
    if (config === null || config === void 0 ? void 0 : config.updatedBySelectedId) {
      Object.assign(item, { id: this.selectedId });
    }
    this._tree.updateItem((config === null || config === void 0 ? void 0 : config.forceDefaultValues) ? this.applyDefaultValues(item) : item);
    this.updateItemInIndexedList(item, config === null || config === void 0 ? void 0 : config.forceDefaultValues);
    const node = (_a = this._tree) === null || _a === void 0 ? void 0 : _a.getNode(this.selectedId);
    if (node == undefined) {
      this.value = this._visibleItems ? this._visibleItems[0] : undefined;
      this._tree.collapseAll();
    }
    if (((_b = this.value) === null || _b === void 0 ? void 0 : _b.id) === item.id) {
      this.value = item;
      this.ezChange.emit(this.value);
      return;
    }
    const childSelected = this.getItemById((_c = this.value) === null || _c === void 0 ? void 0 : _c.id, [item]);
    if (childSelected) {
      this.value = childSelected;
      this.ezChange.emit(this.value);
    }
  }
  /**
   * Remove um item da árvore pelo seu ID.
   * Se o item removido estiver selecionado, a seleção será limpa.
   */
  async removeItem(id) {
    var _a;
    id = id !== null && id !== void 0 ? id : this.selectedId;
    if (!id) {
      return;
    }
    this._tree.removeItem(id);
    this.removeItemFromIndexedList(id);
    this.ezRemoveItem.emit(id);
    if (((_a = this.value) === null || _a === void 0 ? void 0 : _a.id) === id) {
      this.value = undefined;
    }
  }
  /**
   * Obtem um item pelo id
   */
  async getItem(id) {
    return new Promise(resolve => {
      const node = this._tree.getNode(id);
      resolve(node === null || node === void 0 ? void 0 : node.item);
    });
  }
  /**
   * Obtem um array do caminho de itens da seleção atual.
   * @returns Retorna um array do caminho de itens da seleção atual.
   */
  async getCurrentPath() {
    var _a, _b, _c;
    const node = (_a = this._tree) === null || _a === void 0 ? void 0 : _a.getNode(this.selectedId);
    if (node == undefined) {
      return;
    }
    const currentPath = [];
    let parentNode;
    let parentItem = (_b = node.parent) === null || _b === void 0 ? void 0 : _b.item;
    currentPath.push(this.getItemPathAttrs(node.item));
    while (parentItem != undefined) {
      currentPath.unshift(this.getItemPathAttrs(parentItem));
      parentNode = this._tree.getNode(parentItem.id);
      parentItem = (_c = parentNode === null || parentNode === void 0 ? void 0 : parentNode.parent) === null || _c === void 0 ? void 0 : _c.item;
    }
    return currentPath;
  }
  /**
   * Obtem o item pai a partir de um id
   */
  async getParent(id) {
    return new Promise(resolve => {
      var _a;
      const node = this._tree.getNode(id);
      if (node) {
        resolve((_a = node.parent) === null || _a === void 0 ? void 0 : _a.item);
      }
      resolve(undefined);
    });
  }
  observeItems(newValue, oldValue) {
    if (ObjectUtils.objectToString(newValue) !== ObjectUtils.objectToString(oldValue)) {
      this._tree.load(this.items || []);
    }
  }
  observeValue() {
    var _a;
    this.ezChange.emit(this.value);
    this.selectedId = (_a = this.value) === null || _a === void 0 ? void 0 : _a.id;
  }
  onKeyDownListener(event) {
    if (!this.value) {
      return;
    }
    let stop = false;
    switch (event.key) {
      case "ArrowUp":
        this.previousItem();
        stop = true;
        break;
      case "ArrowDown":
        this.nextItem();
        stop = true;
        break;
      case "ArrowLeft":
        this.previousLevel();
        stop = true;
        break;
      case "ArrowRight":
        this.nextLevel();
        stop = true;
        break;
      case " ":
        this.openClose(this.value);
        stop = true;
        break;
    }
    if (stop) {
      event.stopPropagation();
      event.preventDefault();
    }
  }
  getItemById(id, items) {
    for (const treeItem of items) {
      if (treeItem.id === id) {
        return treeItem;
      }
      else if (treeItem.children && Array.isArray(treeItem.children)) {
        const itemFound = this.getItemById(id, treeItem.children);
        if (itemFound) {
          return itemFound;
        }
      }
    }
    return undefined;
  }
  addItemInIndexedList(parentId, item, items) {
    var _a, _b;
    items = (_a = items !== null && items !== void 0 ? items : this.items) !== null && _a !== void 0 ? _a : [];
    if (!parentId) {
      items.push(item);
    }
    const itemFound = this.getItemById(parentId, items);
    itemFound.children = ((_b = itemFound.children) !== null && _b !== void 0 ? _b : []);
    itemFound.children.push(item);
    itemFound.childrenCount = itemFound.children.length;
  }
  applyDefaultValues(item) {
    if (item.disabled === undefined) {
      item.disabled = false;
    }
    if (item.expanded === undefined) {
      item.expanded = false;
    }
    return item;
  }
  updateItemInIndexedList(item, forceDefaultValues = false) {
    if (!item || !this.items) {
      return;
    }
    const itemFound = this.getItemById(item.id, this.items);
    if (itemFound) {
      Object.assign(itemFound, forceDefaultValues ? this.applyDefaultValues(item) : item);
    }
  }
  removeItemFromIndexedList(id, items) {
    var _a;
    items = (_a = items !== null && items !== void 0 ? items : this.items) !== null && _a !== void 0 ? _a : [];
    if (!id) {
      return false;
    }
    const rootIndex = items.findIndex(item => item.id === id);
    if (rootIndex !== -1) {
      items.splice(rootIndex, 1);
      return true;
    }
    for (const treeItem of items) {
      if (treeItem.children && Array.isArray(treeItem.children)) {
        const childIndex = treeItem.children.findIndex(child => child.id === id);
        if (childIndex !== -1) {
          treeItem.children.splice(childIndex, 1);
          treeItem.childrenCount = treeItem.children.length;
          return true;
        }
        if (this.removeItemFromIndexedList(id, treeItem.children)) {
          return true;
        }
      }
    }
    return false;
  }
  getItemPathAttrs({ id, label }) {
    return { id, label };
  }
  openClose(item) {
    if (item == undefined) {
      return;
    }
    const expanded = !item.expanded;
    item.expanded = expanded;
    if (expanded) {
      this.ezOpenItem.emit(item);
    }
    this._tree.updateItem(item);
  }
  previousLevel() {
    var _a;
    if (!this.value) {
      return;
    }
    if (this.value.expanded) {
      this.value.expanded = false;
      this._tree.updateItem(this.value);
    }
    else {
      const node = this._tree.getNode(this.value.id);
      const parentItem = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.item;
      if (parentItem) {
        this.value = parentItem;
      }
    }
  }
  nextLevel() {
    if (!this.value) {
      return;
    }
    const node = this._tree.getNode(this.value.id);
    if (!node.isExpandable()) {
      return;
    }
    if (this.value.expanded) {
      this.nextItem();
    }
    else {
      this.value.expanded = true;
      this._tree.updateItem(this.value);
    }
  }
  indexOf(id) {
    if (id == undefined) {
      return -1;
    }
    for (let i = 0; i < this._visibleItems.length; i++) {
      const item = this._visibleItems[i];
      if (item.id === id) {
        return i;
      }
    }
    return -1;
  }
  selectNextItem(indexIncrement) {
    var _a;
    const nextIndex = this.indexOf((_a = this.value) === null || _a === void 0 ? void 0 : _a.id) + indexIncrement;
    if (nextIndex > -1 && nextIndex < this._visibleItems.length) {
      this.value = this._visibleItems[nextIndex];
    }
  }
  nextItem() {
    this.selectNextItem(1);
  }
  previousItem() {
    this.selectNextItem(-1);
  }
  connectedCallback() {
    if (this.items) {
      this._tree.load(this.items);
    }
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  componentWillRender() {
    var _a;
    if (!this.selectedId || ((_a = this.value) === null || _a === void 0 ? void 0 : _a.id) === this.selectedId) {
      return;
    }
    const node = this._tree.getNode(this.selectedId);
    if (node) {
      this.value = node.item;
    }
  }
  render() {
    ElementIDUtils.addIDInfoIfNotExists(this._element, 'ezTree');
    if (this.items == undefined) {
      return;
    }
    this._visibleItems = [];
    return (h(Host, { tabindex: "-1" }, this._waintingForLoad ?
      h("label", null, this.i18n("app.loading"), "...")
      :
        this._tree.getChildren().map(node => {
          var _a;
          return h(TreeItem, { selectedId: (_a = this.value) === null || _a === void 0 ? void 0 : _a.id, node: node, itemClick: this._onItemClick, iconClick: this._onIconClick, iconResolver: this.iconResolver, tooltipResolver: this.tooltipResolver || defaultTooltipResolver, itemsList: this._visibleItems, itemDoubleClick: (item) => this.ezDbClickItem.emit(item) });
        })));
  }
  get _element() { return getElement(this); }
  static get watchers() { return {
    "items": ["observeItems"],
    "value": ["observeValue"]
  }; }
};
EzTree.style = ezTreeCss;

export { EzTree as ez_tree };
