import { StringUtils } from '@sankhyalabs/core';
import { Host, h } from '@stencil/core';
import Split from 'split-grid';
export class SplitPanel {
  constructor() {
    this._items = [];
    this._buildInProgress = false;
    this.direction = 'column';
    this.anchorToExpand = false;
    this.structural = false;
  }
  rebuildLayout() {
    Array.from(this._element.querySelectorAll(".ez-split-gutter")).reverse().forEach(el => {
      el.remove();
    });
    Array.from(this._element.getElementsByTagName("EzSplitPanel")).reverse().forEach(el => {
      el['rebuildLayout']();
    });
    this.buildItems();
    this.initSplit();
  }
  buildItems() {
    this._panelID = StringUtils.generateUUID();
    this._element.dataset.panelId = this._panelID;
    this._element.dataset.uniqueId = "EzSplitPanel";
    let itemsElements = Array.from(this._element.children);
    this._items = itemsElements.filter(child => { var _a; return ((_a = child.tagName) === null || _a === void 0 ? void 0 : _a.toUpperCase()) === 'EZ-SPLIT-ITEM'; });
    let trackCount = 1;
    this._items.forEach((item, index) => {
      item.dataset.trackNumber = trackCount.toString();
      if (this._items.length > 1 && index != this._items.length - 1) {
        this.addItemGutter(item);
      }
      trackCount += 2;
    });
  }
  componentDidLoad() {
    this.buildItems();
    this.initSplit();
    this._mutationObserver = new MutationObserver((mutationsList) => {
      for (const mutation of mutationsList) {
        if (mutation.type === 'childList' && !this._buildInProgress) {
          this._buildInProgress = true;
          window.requestAnimationFrame(() => {
            this.rebuildLayout();
          });
          window.requestAnimationFrame(() => this._buildInProgress = false);
          break;
        }
      }
    });
    // Configure o observer para observar mudanças nos filhos
    this._mutationObserver.observe(this._element, { childList: true, subtree: false });
  }
  disconnectedCallback() {
    //disconect o _mutationObserver
    if (this._mutationObserver != undefined) {
      this._mutationObserver.disconnect();
    }
  }
  initSplit() {
    if (!this._items.length) {
      return;
    }
    this._element.style[this.direction === 'row' ? 'grid-template-rows' : 'grid-template-columns'] = this.getGridTemplate();
    this.removeGuttersMargin();
    Split(this.getGutters());
  }
  handlePanelDragEnd() {
    const items = this._items.map(item => ({
      id: item.id,
      height: item.clientHeight,
      width: item.clientWidth,
    }));
    this.resizeEnd.emit({ panelId: this._element.id, items });
  }
  getGutters() {
    const gutters = {
      columnGutters: [],
      rowGutters: [],
      onDragEnd: () => this.handlePanelDragEnd()
    };
    if (!this._items.length) {
      return gutters;
    }
    const proToChange = this.direction === 'row' ? 'rowGutters' : 'columnGutters';
    this._items.forEach((item, index) => {
      if (index === this._items.length - 1)
        return;
      let gutterTrack = item.dataset.trackNumber;
      if (index === this._items.length - 1) {
        gutterTrack = this._items.length.toString();
      }
      gutters[proToChange].push({
        track: Number(gutterTrack),
        element: this._element.querySelector(`ez-split-panel[data-panel-id="${this._panelID}"] > [data-item-track="${item.dataset.trackNumber}"]`),
      });
    });
    return gutters;
  }
  addItemGutter(item) {
    const gutter = document.createElement('div');
    gutter.classList.add('ez-split-gutter');
    gutter.classList.add(this.direction);
    if (this.direction === 'row') {
      gutter.classList.add('ez-split-gutter__row');
    }
    else {
      gutter.classList.add('ez-split-gutter__column');
    }
    gutter.dataset.itemTrack = `${item.dataset.trackNumber}`;
    gutter.dataset.trackNumber = (Number(item.dataset.trackNumber) + 1).toString();
    item.parentNode.insertBefore(gutter, item.nextSibling);
  }
  getElementStyle() {
    const style = {
      display: 'grid',
      height: '100%',
      width: '100%',
      position: this.anchorToExpand ? 'relative' : 'unset',
    };
    return style;
  }
  calcFreeSpacePercentage() {
    const inUseSpacePercentage = this._items.reduce((accumulator, currentValue) => {
      var _a;
      return accumulator + (((_a = currentValue.size) === null || _a === void 0 ? void 0 : _a.includes('%')) ? Number(currentValue.size.replace("%", "")) : 0);
    }, 0);
    const itemsWithoutSizeAmount = this._items.filter((item) => item.size === undefined).length;
    if (!itemsWithoutSizeAmount || !inUseSpacePercentage) {
      return null;
    }
    const freeSpacePercentage = ((100 - inUseSpacePercentage) / itemsWithoutSizeAmount);
    return freeSpacePercentage;
  }
  getGridTemplate() {
    let template = '';
    const freeSpacePercentage = this.calcFreeSpacePercentage();
    this._items.forEach((col, index) => {
      let size = col.size || '1fr';
      if (!col.size && freeSpacePercentage) {
        size = `${freeSpacePercentage}%`;
      }
      if (index === this._items.length - 1) {
        template += ` ${size}`;
        return;
      }
      if (index === 0) {
        template += `${size} 5px`;
        return;
      }
      template += ` ${size} 5px`;
    });
    return template;
  }
  removeGuttersMargin() {
    if (this._items.length <= 1)
      return;
    if (this.direction == "column") {
      this.removeGuttersMarginColumn();
      return;
    }
    if (this.direction == "row") {
      this.removeGuttersMarginRow();
      return;
    }
  }
  removeGuttersMarginColumn() {
    this._items.forEach((item, index) => {
      if (index == 0) {
        item.style.marginRight = "0";
        return;
      }
      if (index === this._items.length - 1) {
        item.style.marginLeft = "0";
        return;
      }
      item.style.marginRight = "0";
      item.style.marginLeft = "0";
      return;
    });
  }
  removeGuttersMarginRow() {
    if (this._items.length <= 1)
      return;
    this._items.forEach((item, index) => {
      if (index == 0) {
        item.style.marginBottom = "0";
        return;
      }
      if (index === this._items.length - 1) {
        item.style.marginTop = "0";
        return;
      }
      item.style.marginBottom = "0";
      item.style.marginTop = "0";
      return;
    });
  }
  render() {
    return h(Host, { class: `${this.structural ? 'structural__panel' : 'content__panel'}`, style: this.getElementStyle() });
  }
  static get is() { return "ez-split-panel"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-split-panel.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-split-panel.css"]
    };
  }
  static get properties() {
    return {
      "direction": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "'row' | 'column'",
          "resolved": "\"column\" | \"row\"",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "direction",
        "reflect": false,
        "defaultValue": "'column'"
      },
      "anchorToExpand": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Respons\u00E1vel por definir o painel que limita o tamanho do item expandido."
        },
        "attribute": "anchor-to-expand",
        "reflect": false,
        "defaultValue": "false"
      },
      "structural": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o painel est\u00E1 sendo utilizado como estrutura para apresenta\u00E7\u00E3o de outro item"
        },
        "attribute": "structural",
        "reflect": false,
        "defaultValue": "false"
      }
    };
  }
  static get events() {
    return [{
        "method": "resizeEnd",
        "name": "resizeEnd",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "IPanelSizeInfo",
          "resolved": "IPanelSizeInfo",
          "references": {
            "IPanelSizeInfo": {
              "location": "global"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "rebuildLayout": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {},
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
}
