import { h, Host } from '@stencil/core';
import { ApplicationContext, ArrayUtils, ElementIDUtils, ServiceUtils, StorageType } from '@sankhyalabs/core';
import { DataFetcher } from '../../lib/http/data-fetcher/DataFetcher';
import ExecutorFactory from './actions/factory/executor.factory';
import Actions from './actions';
import ClientEventConfirm from './clientEvent';
import ResourceIDUtils from '../../lib/resourceid/ResourceIDUtils';
export class SnkActionsButton {
  constructor() {
    this.CLIENT_EVENT_CONFIRM_NAME = "br.com.sankhya.actionbutton.clientconfirm";
    this._actions = [];
    this.handleClick = (evt) => {
      const selectedAction = this._actions.find((action) => action.actionID == evt.detail.id);
      const executor = new ExecutorFactory(selectedAction.type).executor;
      const action = new Actions(executor, this._dataUnit, this._resourceID);
      action.execute(Object.assign({}, selectedAction));
      this._showDropdown = false;
    };
    this._items = [];
    this._showDropdown = false;
  }
  async getActions() {
    const actions = await ServiceUtils.useCacheWithService(`SnkActionsButton_${this._entityName}-${this._resourceID}`, async () => {
      var _a;
      const param = {
        param: {
          entityName: this._entityName,
          resourceID: this._resourceID,
        },
      };
      const result = await DataFetcher.get().callServiceBroker('ActionButtonsSP.getActions', param);
      return ((_a = result.actions) === null || _a === void 0 ? void 0 : _a.action) || [];
    }, StorageType.IN_MEMORY_CACHE);
    this._actions = SnkActionsButton.parameters.isOrderActions
      ? ArrayUtils.sortAlphabetically(actions, 'description')
      : actions;
  }
  controlDropdown() {
    this._showDropdown = !this._showDropdown;
  }
  canShowDropdown() {
    var _a;
    return this._showDropdown && ((_a = this._items) === null || _a === void 0 ? void 0 : _a.length) > 0;
  }
  positionDropdown() {
    var _a;
    const bounding = (_a = this._ezButton) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
    if (!bounding || !this._dropdownParent)
      return;
    this._dropdownParent.style.top = (bounding.y + bounding.height + 5) + "px";
    this._dropdownParent.style.left = bounding.x + "px";
  }
  closeDropdown(evt) {
    const target = evt === null || evt === void 0 ? void 0 : evt.target;
    if (!target)
      return;
    if (!target.closest(".snk-actions-button")) {
      this._showDropdown = false;
    }
  }
  setEvents() {
    document.removeEventListener("click", this.closeDropdown.bind(this));
    document.addEventListener("click", this.closeDropdown.bind(this));
    document.removeEventListener("scroll", this.positionDropdown.bind(this));
    document.addEventListener("scroll", this.positionDropdown.bind(this));
  }
  async componentWillLoad() {
    var _a, _b;
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    await this.loadParameters();
    const snkDataUnit = this._element.parentElement;
    this._dataUnit = snkDataUnit === null || snkDataUnit === void 0 ? void 0 : snkDataUnit.dataUnit;
    this._resourceID = snkDataUnit === null || snkDataUnit === void 0 ? void 0 : snkDataUnit.resourceID;
    this._entityName = (_b = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.split('/')[2];
    if (this._resourceID == undefined) {
      this._resourceID = await ResourceIDUtils.getResourceID();
    }
    this.setEvents();
    await this.getActions();
    this.loadItems();
  }
  async componentDidLoad() {
    if (!this._element)
      return;
    ElementIDUtils.addIDInfo(this._element);
    this.positionDropdown();
    if (!(await this._application.hasClientEvent(this.CLIENT_EVENT_CONFIRM_NAME))) {
      const clientEventConfirm = new ClientEventConfirm();
      this._application.addClientEvent(this.CLIENT_EVENT_CONFIRM_NAME, clientEventConfirm.clientConfirm);
    }
  }
  componentDidUpdate() {
    this.positionDropdown();
  }
  loadItems() {
    if (!this._actions || this._actions.length == 0)
      return;
    this._actions.forEach(action => {
      this._items.push({ id: action.actionID, label: action.description });
    });
  }
  getElementID(sufix) {
    return {
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(sufix)
    };
  }
  async loadParameters() {
    if (SnkActionsButton.parameters.isOrderActions != null)
      return;
    SnkActionsButton.parameters.isOrderActions = await this._application.getBooleanParam('global.ordenar.acoes.personalizadas');
  }
  render() {
    return (h(Host, null, (this._actions && this._actions.length > 0) &&
      (h("div", { class: `ez-padding-left--medium snk-actions-button
                            ${this.canShowDropdown() ? " ez-elevation--16" : ""}
                        ` }, h("ez-button", Object.assign({ ref: (ref) => this._ezButton = ref, iconName: "acao", size: "small", mode: "icon", title: this._application.messagesBuilder.getMessage("snkActionsButton.title.actions", undefined), onClick: () => this.controlDropdown() }, this.getElementID("button"))), h("div", Object.assign({ ref: (ref) => this._dropdownParent = ref, class: `${this.canShowDropdown() ?
          "snk-actions-button__dropdown--show" :
          "snk-actions-button__dropdown"}
                            ` }, this.getElementID("dropdown")), (this.canShowDropdown()) &&
        (h("ez-dropdown", Object.assign({ items: this._items, onEzClick: (evt) => this.handleClick(evt) }, this.getElementID("dropdown"))))))), (this.canShowDropdown()) &&
      (h("div", Object.assign({ class: "ez-scrim ez-scrim--light" }, this.getElementID("ezScrim"))))));
  }
  static get is() { return "snk-actions-button"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-actions-button.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-actions-button.css"]
    };
  }
  static get states() {
    return {
      "_items": {},
      "_showDropdown": {}
    };
  }
  static get elementRef() { return "_element"; }
}
SnkActionsButton.parameters = {
  isOrderActions: null
};
