import { FloatingManager, ElementIDUtils } from '@sankhyalabs/core';
import { h, Host } from '@stencil/core';
import { CSSVarsUtils } from '../../utils';
export class EzActionsButton {
  constructor() {
    this._arrowOffset = 5;
    this.innerClickCheck = (floatingContainer, node) => {
      var _a;
      if (node && floatingContainer) {
        if (node === floatingContainer) {
          return true;
        }
        const children = floatingContainer.children;
        for (let i = 0; i < children.length; i++) {
          if ((_a = children[i].shadowRoot) === null || _a === void 0 ? void 0 : _a.contains(node)) {
            return true;
          }
        }
        do {
          if (floatingContainer.contains(node)) {
            return true;
          }
          node = node.offsetParent;
        } while (node != undefined && node != document.getRootNode());
      }
      return false;
    };
    this._selectedAction = undefined;
    this.enabled = true;
    this.actions = undefined;
    this.size = "medium";
    this.showLabel = false;
    this.displayIcon = undefined;
    this.checkOption = false;
    this.value = undefined;
    this.isTransparent = false;
    this.arrowActive = false;
  }
  /**
   * Oculta a lista de ações.
   */
  async hideActions() {
    if (this._floatingID != undefined) {
      FloatingManager.close(this._floatingID);
    }
    this._floatingID = undefined;
  }
  /**
   * Apresenta a lista de ações.
   */
  async showActions() {
    if (!this.enabled) {
      return;
    }
    const options = this.getFloatOptions();
    this._floatingID = FloatingManager.float(this._actionsList, this._listContainer, options);
    const sideLimit = this.getSideLimit();
    if (sideLimit != undefined) {
      options.left = sideLimit;
      FloatingManager.updateFloatPosition(this._actionsList, this._listContainer, options);
    }
    window.requestAnimationFrame(() => {
      this._actionsList.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "nearest" });
    });
    this.ezPopoverOpen.emit(this._actionsList);
  }
  /**
   * Verifica se a lista de ações está aberta.
   */
  async isOpened() {
    return this._floatingID != undefined;
  }
  getFloatOptions() {
    return {
      autoClose: true,
      innerClickTest: this.innerClickCheck,
      isFixed: true,
      top: this.getPositionTop(),
      left: this.getPositionLeft(),
      backClickListener: () => this._floatingID = undefined
    };
  }
  getSideLimit() {
    var _a;
    const docWidth = document.body.clientWidth;
    const boundingList = (_a = this._actionsList) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
    const rightOffset = docWidth - this._button.getBoundingClientRect().right;
    if ((boundingList === null || boundingList === void 0 ? void 0 : boundingList.right) >= docWidth || (boundingList === null || boundingList === void 0 ? void 0 : boundingList.right) === (docWidth - rightOffset)) {
      return (docWidth - boundingList.width - rightOffset) + "px";
    }
    return;
  }
  updatePosition() {
    if (!this.enabled || this._floatingID == undefined) {
      return;
    }
    const options = this.getFloatOptions();
    const sideLimit = this.getSideLimit();
    if (sideLimit != undefined) {
      options.left = sideLimit;
    }
    FloatingManager.updateFloatPosition(this._actionsList, this._listContainer, options);
  }
  getPositionTop() {
    var _a;
    const boundingHost = (_a = this._element) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
    if (boundingHost == undefined) {
      return null;
    }
    return (boundingHost.y + boundingHost.height) + "px";
  }
  getBoundingLeft() {
    var _a;
    const boundingHost = (_a = this._element) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
    if (boundingHost == undefined) {
      return null;
    }
    const arrowOffset = this.arrowActive ? this._arrowOffset : 0;
    return (boundingHost.x - arrowOffset) + "px";
  }
  getPositionLeft() {
    const boundingLeft = this.getBoundingLeft();
    if (boundingLeft) {
      return boundingLeft;
    }
    else if (this.arrowActive) {
      return `-${this._arrowOffset}px`;
    }
    return null;
  }
  hasLabelOrCheckOption() {
    var _a;
    return (this.showLabel || this.checkOption) && ((_a = this.actions) === null || _a === void 0 ? void 0 : _a.length) > 0;
  }
  hasIconName() {
    var _a;
    return (_a = this.actions) === null || _a === void 0 ? void 0 : _a.some(action => action.iconName != undefined);
  }
  controlScrollPage() {
    window.removeEventListener("scroll", this.updatePosition.bind(this));
    window.addEventListener("scroll", this.updatePosition.bind(this));
  }
  //---------------------------------------------
  // Event handlers
  //---------------------------------------------
  handlerButtonClick() {
    this.showActions();
  }
  actionClick(action) {
    this._selectedAction = action;
    this.hideActions();
    this.ezAction.emit(action);
  }
  //---------------------------------------------
  // Lifecycle web component
  //---------------------------------------------
  componentWillLoad() {
    if (this.actions == undefined) {
      this.actions = [];
      const optionsTags = this._element.querySelectorAll("action");
      if (optionsTags) {
        optionsTags.forEach((e) => {
          let label = e.innerText;
          let value = e.getAttribute("value");
          let enabled = !(e.getAttribute("enabled") === "false");
          if (!value) {
            value = label;
          }
          this.actions.push({ label, value, enabled });
          e.hidden = true;
        });
      }
    }
  }
  disconnectedCallback() {
    this.ezDisconnectedActionButtons.emit();
  }
  componentDidLoad() {
    CSSVarsUtils.applyVarsButton(this._element, this._button);
    ElementIDUtils.addIDInfo(this._element);
    this.controlScrollPage();
  }
  componentDidRender() {
    var _a;
    if (this._floatingID == undefined) {
      (_a = this._actionsList) === null || _a === void 0 ? void 0 : _a.remove();
    }
    if (this.hasLabelOrCheckOption()) {
      if (!!this.value) {
        this._selectedAction = this.actions.find((action) => action.value === this.value);
      }
      else if (!!!this._selectedAction) {
        this._selectedAction = this.actions[0];
      }
    }
  }
  buildActionElement(action) {
    var _a;
    if (!action) {
      return;
    }
    if (action.itemBuilder != undefined) {
      const customContent = action.itemBuilder(this._element, action);
      if (typeof customContent === "string") {
        return h("div", { class: "ez-actions-button__btn-action", innerHTML: customContent });
      }
      return customContent;
    }
    return h("ez-button", { size: "small", label: action.label, onClick: () => this.actionClick(action), enabled: action.enabled, class: "ez-actions-button__btn-action" +
        (this.checkOption || this.hasIconName() ? " ez-actions-button__btn-action--spaced" : "") }, this.checkOption && ((_a = this._selectedAction) === null || _a === void 0 ? void 0 : _a.value) === action.value &&
      h("ez-icon", { class: "ez-actions-button__icon-check", slot: "leftIcon", size: "small", iconName: "check" }), !this.checkOption && action.iconName &&
      h("ez-icon", { class: "ez-actions-button__icon-item", slot: "leftIcon", size: "small", iconName: action.iconName }));
  }
  render() {
    var _a;
    return (h(Host, null, h("ez-button", { ref: elem => this._button = elem, class: (this.isTransparent ? "ez-actions-button__btn-transparent" : "") +
        (this.showLabel ? " ez-actions-button__btn-label" : ""), label: this.showLabel && ((_a = this._selectedAction) === null || _a === void 0 ? void 0 : _a.label), enabled: this.enabled, mode: this.showLabel ? undefined : "icon", iconName: this.showLabel ? "" : this.displayIcon || "dots-vertical", size: this.size, onClick: () => this.handlerButtonClick() }, this.showLabel &&
      h("ez-icon", { class: "ez-actions-button__icon-right", slot: "rightIcon", iconName: this.displayIcon || "dots-vertical" })), h("section", { class: "ez-actions-button__list-container", ref: elem => this._listContainer = elem }, this.arrowActive &&
      h("div", { class: "ez-actions-button__arrow ez-actions-button__arrow--" + (this.size || "small") +
          (this.isTransparent ? " ez-actions-button__arrow--upped" : "") }), h("div", { ref: elem => this._actionsList = elem, class: "ez-actions-button__actions-list ez-actions-button__actions-list--max-height" +
        (this.arrowActive && !this.isTransparent ? " ez-actions-button__actions-list--lowered" : "") }, this.actions.map(action => this.buildActionElement(action))))));
  }
  static get is() { return "ez-actions-button"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-actions-button.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-actions-button.css"]
    };
  }
  static get properties() {
    return {
      "enabled": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se false o usu\u00E1rio n\u00E3o pode interagir com o componente."
        },
        "attribute": "enabled",
        "reflect": true,
        "defaultValue": "true"
      },
      "actions": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "Array<IAction>",
          "resolved": "IAction[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "IAction": {
              "location": "import",
              "path": "../../utils"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a lista de a\u00E7\u00F5es. Os elementos devem obedecer\no formato: `{value: string, label: string}`."
        }
      },
      "size": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "\"small\" | \"medium\" | \"large\"",
          "resolved": "\"large\" | \"medium\" | \"small\"",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Determina o tamanho do ez-action-button."
        },
        "attribute": "size",
        "reflect": true,
        "defaultValue": "\"medium\""
      },
      "showLabel": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se true o label ser\u00E1 apresentado."
        },
        "attribute": "show-label",
        "reflect": true,
        "defaultValue": "false"
      },
      "displayIcon": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o \u00EDcone do componente."
        },
        "attribute": "display-icon",
        "reflect": true
      },
      "checkOption": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se true o check ser\u00E1 apresentado para os itens."
        },
        "attribute": "check-option",
        "reflect": true,
        "defaultValue": "false"
      },
      "value": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o valor do componente."
        },
        "attribute": "value",
        "reflect": true
      },
      "isTransparent": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se true o background ser\u00E1 transparent."
        },
        "attribute": "is-transparent",
        "reflect": true,
        "defaultValue": "false"
      },
      "arrowActive": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se true a seta de ordena\u00E7\u00E3o ser\u00E1 apresentada."
        },
        "attribute": "arrow-active",
        "reflect": true,
        "defaultValue": "false"
      }
    };
  }
  static get states() {
    return {
      "_selectedAction": {}
    };
  }
  static get events() {
    return [{
        "method": "ezAction",
        "name": "ezAction",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido ao acionar uma a\u00E7\u00E3o."
        },
        "complexType": {
          "original": "IAction",
          "resolved": "IAction",
          "references": {
            "IAction": {
              "location": "import",
              "path": "../../utils"
            }
          }
        }
      }, {
        "method": "ezPopoverOpen",
        "name": "ezPopoverOpen",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido ao mostrar a lista de a\u00E7\u00F5es"
        },
        "complexType": {
          "original": "HTMLElement",
          "resolved": "HTMLElement",
          "references": {
            "HTMLElement": {
              "location": "global"
            }
          }
        }
      }, {
        "method": "ezDisconnectedActionButtons",
        "name": "ezDisconnectedActionButtons",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando componente \u00E9 desconectado da DOM"
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "hideActions": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Oculta a lista de a\u00E7\u00F5es.",
          "tags": []
        }
      },
      "showActions": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Apresenta a lista de a\u00E7\u00F5es.",
          "tags": []
        }
      },
      "isOpened": {
        "complexType": {
          "signature": "() => Promise<boolean>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<boolean>"
        },
        "docs": {
          "text": "Verifica se a lista de a\u00E7\u00F5es est\u00E1 aberta.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
}
