import { h, proxyCustomElement, HTMLElement, createEvent, Host } from '@stencil/core/internal/client';
import { Action, ElementIDUtils, LockManager, LockManagerOperation, SilentException, StringUtils, OVERFLOWED_CLASS_NAME, OverflowWatcher, OverflowDirection, ApplicationContext } from '@sankhyalabs/core';
import { P as PresentationMode } from './ISave.js';
import { A as AuthorizationConfig } from './AuthorizationConfig.js';
import { s as store } from './index2.js';
import { d as defineCustomElement$6 } from './snk-actions-button2.js';
import { d as defineCustomElement$5 } from './snk-data-exporter2.js';
import { d as defineCustomElement$4 } from './snk-exporter-email-sender2.js';
import { d as defineCustomElement$3 } from './snk-taskbar-skeleton2.js';
import { d as defineCustomElement$2 } from './taskbar-actions-button2.js';
import { d as defineCustomElement$1 } from './taskbar-split-button2.js';

var TaskbarElement;
(function (TaskbarElement) {
  TaskbarElement["PREVIOUS"] = "PREVIOUS";
  TaskbarElement["NEXT"] = "NEXT";
  TaskbarElement["REFRESH"] = "REFRESH";
  TaskbarElement["UPDATE"] = "UPDATE";
  TaskbarElement["CLONE"] = "CLONE";
  TaskbarElement["REMOVE"] = "REMOVE";
  TaskbarElement["INSERT"] = "INSERT";
  TaskbarElement["CANCEL"] = "CANCEL";
  TaskbarElement["SAVE"] = "SAVE";
  TaskbarElement["GRID_MODE"] = "GRID_MODE";
  TaskbarElement["FORM_MODE"] = "FORM_MODE";
  TaskbarElement["MORE_OPTIONS"] = "MORE_OPTIONS";
  TaskbarElement["DIVIDER"] = "DIVIDER";
  TaskbarElement["SPACER"] = "SPACER";
  TaskbarElement["CONFIGURATOR"] = "CONFIGURATOR";
  TaskbarElement["DATA_EXPORTER"] = "DATA_EXPORTER";
  TaskbarElement["ATTACH"] = "ATTACH";
  TaskbarElement["ACTIONS_BUTTON"] = "ACTIONS_BUTTON";
  TaskbarElement["UPDATE_MULTIPLE"] = "UPDATE_MULTIPLE";
})(TaskbarElement || (TaskbarElement = {}));
var AuthorizationElements;
(function (AuthorizationElements) {
  AuthorizationElements["UPDATE"] = "UPDATE";
  AuthorizationElements["CLONE"] = "CLONE";
  AuthorizationElements["REMOVE"] = "REMOVE";
  AuthorizationElements["INSERT"] = "INSERT";
  AuthorizationElements["CONFIGURATOR"] = "CONFIGURATOR";
})(AuthorizationElements || (AuthorizationElements = {}));
var VisibleWhenForbidden;
(function (VisibleWhenForbidden) {
  VisibleWhenForbidden["CONFIGURATOR"] = "CONFIGURATOR";
})(VisibleWhenForbidden || (VisibleWhenForbidden = {}));
const buildCustomButton = ({ def, className, dataElementId, action, isEnabled, size }) => {
  const { hint, text, iconName } = def;
  if (iconName) {
    if (text) {
      return iconTextButton({ iconName, element: def.name, className, dataElementId, title: hint, action, isEnabled, size });
    }
    else {
      return iconButton({ iconName, element: def.name, className, dataElementId, title: hint, action, isEnabled, size });
    }
  }
  else {
    return textButton({ element: def.name, className, dataElementId, title: hint, action, isEnabled, size });
  }
};
const buildElem = ({ element, className, dataElementId, getTitle, action, isEnabled, actions, dataExporterStoreKey, presentationMode, variant, size }) => {
  var _a, _b;
  const title = getTitle(element);
  const propertiesItem = {
    element, className, dataElementId, title, action, isEnabled, actions, variant, size
  };
  switch (element) {
    case TaskbarElement.PREVIOUS:
      return iconButton(Object.assign({ iconName: "chevron-left" }, propertiesItem));
    case TaskbarElement.NEXT:
      return iconButton(Object.assign({ iconName: "chevron-right" }, propertiesItem));
    case TaskbarElement.REFRESH:
      return iconButton(Object.assign({ iconName: "sync" }, propertiesItem));
    case TaskbarElement.UPDATE:
      return iconButton(Object.assign({ iconName: "edit" }, propertiesItem));
    case TaskbarElement.UPDATE_MULTIPLE:
      return iconButton(Object.assign({ iconName: "edit-table" }, propertiesItem));
    case TaskbarElement.CLONE:
      return iconButton(Object.assign({ iconName: "copy" }, propertiesItem));
    case TaskbarElement.REMOVE:
      return iconButton(Object.assign({ iconName: "delete" }, propertiesItem));
    case TaskbarElement.INSERT:
      if (presentationMode === PresentationMode.PRIMARY) {
        return textButton(Object.assign({}, propertiesItem));
      }
      else {
        return iconButton(Object.assign({ iconName: "plus" }, propertiesItem));
      }
    case TaskbarElement.CANCEL:
      return textButton(Object.assign({}, propertiesItem));
    case TaskbarElement.SAVE:
      if (presentationMode === PresentationMode.PRIMARY) {
        return iconTextButton(Object.assign(Object.assign({ iconName: "save" }, propertiesItem), { variant: "primary" }));
      }
      else {
        return iconButton(Object.assign(Object.assign({ iconName: "save" }, propertiesItem), { variant: "primary" }));
      }
    case TaskbarElement.GRID_MODE:
      return iconButton(Object.assign({ iconName: "table" }, propertiesItem));
    case TaskbarElement.FORM_MODE:
      return iconButton(Object.assign({ iconName: "list" }, propertiesItem));
    case TaskbarElement.CONFIGURATOR:
      if ((actions === null || actions === void 0 ? void 0 : actions.length) > 0) {
        return splitButton(Object.assign({ iconName: "settings-inverted" }, propertiesItem));
      }
      return iconButton(Object.assign({ iconName: "settings-inverted" }, propertiesItem));
    case TaskbarElement.MORE_OPTIONS:
      const definedActions = (_a = actions === null || actions === void 0 ? void 0 : actions.filter(a => a !== undefined)) !== null && _a !== void 0 ? _a : [];
      return actionButton(Object.assign(Object.assign({}, propertiesItem), { actions: definedActions }));
    case TaskbarElement.DIVIDER:
      return h("hr", { class: "ez-divider-vertical ez-divider--dark ez-margin--none ez-margin-left--medium", "data-taskbar-divider": true });
    case TaskbarElement.DATA_EXPORTER:
      const provider = (_b = store.get("exporterProviders")) === null || _b === void 0 ? void 0 : _b[dataExporterStoreKey];
      return h("snk-data-exporter", { class: className, provider: provider, "data-element-id": dataElementId, "data-taskbar-element": element, size: size });
    case TaskbarElement.ATTACH:
      return iconButton(Object.assign({ iconName: "anexo" }, propertiesItem));
    case TaskbarElement.ACTIONS_BUTTON:
      return h("snk-actions-button", { "data-element-id": dataElementId, "data-taskbar-element": element, class: className, size: size });
  }
};
function textButton({ action, className, dataElementId, title, element, isEnabled, variant, size }) {
  return (h("ez-tooltip", { key: dataElementId, message: title, class: className },
    h("ez-button", { label: title, "data-taskbar-label": title, "data-taskbar-element": element, "data-element-id": dataElementId, isDisabled: !isEnabled(element), onClick: () => action(element), variant: variant, size: size })));
}
function concatClass(className) {
  if (typeof className === "string") {
    return className;
  }
  else {
    return Object.keys(className).filter(key => className[key]).join(" ");
  }
}
function iconButton({ iconName, element, className, dataElementId, title, action, isEnabled, variant, size }) {
  return (h("ez-tooltip", { key: dataElementId, message: title, class: {
      [concatClass(className)]: true,
      [`icon-button--${size}`]: true
    } },
    h("ez-button", { mode: "icon", "data-taskbar-label": title, "data-taskbar-element": element, "data-taskbar-icon": iconName, "data-element-id": dataElementId, iconName: iconName, isDisabled: !isEnabled(element), onClick: () => action(element), variant: variant, size: size })));
}
function iconTextButton({ iconName, element, className, dataElementId, title, action, isEnabled, variant, size }) {
  return (h("ez-tooltip", { key: dataElementId, message: title, class: className },
    h("ez-button", { label: title, "data-taskbar-label": title, "data-taskbar-icon": iconName, "data-taskbar-element": element, "data-element-id": dataElementId, isDisabled: !isEnabled(element), onClick: () => action(element), variant: variant, size: size },
      h("ez-icon", { class: "ez-padding-right--small", slot: "leftIcon", iconName: iconName }))));
}
function splitButton({ iconName, element, className, title, dataElementId, isEnabled, actions, action, size }) {
  return actions && actions.length > 0
    ?
      h("taskbar-split-button", { key: dataElementId, class: className, iconName: iconName, "data-taskbar-icon": iconName, "data-taskbar-label": title, title: title, "data-taskbar-element": element, "data-element-id": dataElementId, enabled: isEnabled(element), actions: actions, action: () => action(element), size: size })
    : undefined;
}
function actionButton({ element, className, dataElementId, title, isEnabled, actions, action, size }) {
  return actions && actions.length > 0
    ? h("taskbar-actions-button", { class: className, key: dataElementId, title: title, "data-taskbar-element": element, "data-element-id": dataElementId, enabled: isEnabled(element), actions: actions, onTaskbarActionSelected: (evt) => action(evt.detail.value), size: size })
    : undefined;
}

const snkTaskbarCss = ".sc-snk-taskbar-h{display:flex;flex-wrap:nowrap}.no-wrap.sc-snk-taskbar-h{flex-wrap:nowrap}.full-width.sc-snk-taskbar-h{width:100%}.align-right.sc-snk-taskbar-h{justify-content:flex-end}.overflowed.sc-snk-taskbar{display:none}.taskbar-element.sc-snk-taskbar{width:auto}.space-between-item.sc-snk-taskbar{margin-left:var(--space--8, 8px)}.icon-button--small.sc-snk-taskbar{width:32px;height:32px}.icon-button--medium.sc-snk-taskbar{width:42px;height:42px}.icon-button--large.sc-snk-taskbar{width:46px;height:46px}.taskbar-spacer.sc-snk-taskbar{flex:1}.taskbar-group.sc-snk-taskbar{display:flex;flex-wrap:wrap;min-width:0}.taskbar-group--start.sc-snk-taskbar{flex:1 1 auto;justify-content:flex-start}.taskbar-group--end.sc-snk-taskbar{flex:0 0 auto;justify-content:flex-end}";

const SnkTaskbar = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.actionClick = createEvent(this, "actionClick", 7);
    this.taskbarSaveLocker = createEvent(this, "taskbarSaveLocker", 7);
    this.taskbarSaveUnlocker = createEvent(this, "taskbarSaveUnlocker", 7);
    this.TASKBAR_ITEM_ID_PREFIX = 'TASKBAR_ITEM_';
    this.TASKBAR_CUSTOM_ELEMENTS_CONTAINER_CLASS_NAME = 'taskbar-custom-elements-container';
    this.NOT_OVERFLOW_ELEMENTS = ["moreOptions", "dataExporter_snkDataExporter", "actionsButton_snkActionsButton"];
    this.TASKBAR_CUSTOM_ELEMENTS = 'taskbar-custom-elements-container';
    this.TASKBAR_ADDITIONAL_SLOT_CONTAINER_CLASS_NAME = 'taskbar-additional-slot-container';
    this.TASKBAR_ADDITIONAL_SLOT = 'taskbar-additional-slot-container';
    this._dataUnitInitialized = false;
    this._permissions = {};
    this._customElements = new Map();
    this._customElementsId = [];
    this._overFlowedElements = [];
    this._titleKeyByElement = {
      [TaskbarElement.UPDATE_MULTIPLE]: "snkTaskbar.titleUpdateMultiple",
      [TaskbarElement.UPDATE]: "snkTaskbar.titleUpdate",
      [TaskbarElement.PREVIOUS]: "snkTaskbar.titlePrevious",
      [TaskbarElement.NEXT]: "snkTaskbar.titleNext",
      [TaskbarElement.REFRESH]: "snkTaskbar.titleRefresh",
      [TaskbarElement.CLONE]: "snkTaskbar.titleClone",
      [TaskbarElement.REMOVE]: "snkTaskbar.titleRemove",
      [TaskbarElement.MORE_OPTIONS]: "snkTaskbar.titleMoreOptions",
      [TaskbarElement.INSERT]: "snkTaskbar.titleInsert",
      [TaskbarElement.CANCEL]: "snkTaskbar.titleCancel",
      [TaskbarElement.SAVE]: "snkTaskbar.titleSave",
      [TaskbarElement.GRID_MODE]: "snkTaskbar.titleGridMode",
      [TaskbarElement.FORM_MODE]: "snkTaskbar.titleFormMode",
      [TaskbarElement.CONFIGURATOR]: "snkTaskbar.titleConfigurator",
      [TaskbarElement.ATTACH]: "snkTaskbar.titleAttach",
    };
    this.onSaveEvent = (action) => {
      switch (action.type) {
        case Action.FIELD_INVALIDATED:
        case Action.INVALIDATE_CLEAN:
        case Action.DATA_SAVED:
        case Action.SAVING_ERROR:
        case Action.SAVING_CANCELED:
          this._isWaitingForSave = false;
          break;
        case Action.SAVING_DATA:
          this._isWaitingForSave = true;
          break;
      }
    };
    this._hiddenActionsList = [];
    this._isWaitingForSave = false;
    this._isLoading = true;
    this.alignRigth = false;
    this.customSlotId = "TASKBAR_CUSTOM_ELEMENTS";
    this.additionalSlotId = "TASKBAR_ADDITIONAL_SLOT";
    this.customContainerId = undefined;
    this.overflowStrategy = 'hiddenItems';
    this.configName = undefined;
    this.resourceID = undefined;
    this.buttons = undefined;
    this.customButtons = undefined;
    this.actionsList = undefined;
    this.actionsSettingsList = undefined;
    this.customActionsList = undefined;
    this.primaryButton = undefined;
    this.disabledButtons = undefined;
    this.dataUnit = undefined;
    this.presentationMode = PresentationMode.PRIMARY;
    this.messagesBuilder = undefined;
    this.disableSkeleton = false;
    this.sizeButtons = 'small';
  }
  handleCustomSlotElementsLoaded(event) {
    if (this.hasToSearchCustomElements(event)) {
      this.getCustomElements(true);
    }
  }
  handleTaskbarSaveLocker() {
    if (this._isWaitingForSave !== true) {
      this._isWaitingForSave = true;
    }
  }
  handleTaskbarSaveUnlocker() {
    if (this._isWaitingForSave === true) {
      this._isWaitingForSave = false;
    }
  }
  hasToSearchCustomElements(event) {
    return this.customSlotId === event.detail && !this._slotContainer;
  }
  observeButtons() {
    this.handleDefinitions();
  }
  observeDisabledButtons() {
    this.handleDefinitions();
  }
  observeIsWaitingForSave(newValue, oldValue) {
    if (newValue == true && oldValue == false) {
      this.taskbarSaveLocker.emit();
    }
    if (newValue == false && oldValue == true) {
      this.taskbarSaveUnlocker.emit();
    }
  }
  observeDataUnit(newValue) {
    this.initializeDataUnit(newValue);
  }
  initializeDataUnit(dataUnit = this.dataUnit) {
    if (!!dataUnit && !this._dataUnitInitialized) {
      this._dataUnitInitialized = true;
      const dataInfo = { dataUnit: this.dataUnit };
      ElementIDUtils.addIDInfo(this._element, null, dataInfo);
      this.dataUnit.subscribe(this.onSaveEvent);
    }
  }
  elementsFromString(strButtons) {
    const elements = [];
    if (strButtons == null)
      return elements;
    strButtons.split(",").forEach(buttonName => {
      buttonName = buttonName.trim();
      if (VisibleWhenForbidden[buttonName] || this.isAllowed(buttonName)) {
        elements.push(buttonName.trim());
      }
    });
    return elements;
  }
  isAllowed(buttonName) {
    if (!this._permissions) {
      return false;
    }
    if (this._permissions.isSup) {
      return true;
    }
    if (buttonName === AuthorizationElements.CONFIGURATOR) {
      return this._permissions[AuthorizationConfig.CONFIG_GRID] || this._permissions[AuthorizationConfig.CONFIG];
    }
    if (AuthorizationElements[buttonName]) {
      return this._permissions[buttonName];
    }
    return true;
  }
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno modulo na estrutura da aplicação:
   * - Criar um arquivo no seguinte caminho: /messages/appmessages.msg.js.
   * Para conhecer os detalhes do módulo, vide o arquivo neste projeto "/src/lib/message/resources/snk-taskbar.msg.ts"
   */
  getTitle(element) {
    var _a;
    let key;
    if (this.isAllowed(element)) {
      key = this._titleKeyByElement[element];
    }
    else {
      key = "snkTaskbar.forbidden";
    }
    return key ? (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, {}) : "";
  }
  elementClick(elem) {
    LockManager.whenResolve(this._element, LockManagerOperation.TASKBAR_CLICK).then(() => {
      if (!this.dataUnit) {
        return;
      }
      switch (elem) {
        case TaskbarElement.PREVIOUS:
          this.dataUnit.previousRecord();
          break;
        case TaskbarElement.NEXT:
          this.dataUnit.nextRecord();
          break;
        case TaskbarElement.REFRESH:
          this.dataUnit.loadData();
          break;
        case TaskbarElement.CLONE:
          this.dataUnit.copySelected();
          break;
        case TaskbarElement.REMOVE:
          this.dataUnit.removeSelectedRecords();
          break;
        case TaskbarElement.INSERT:
          this.dataUnit.addRecord();
          break;
        case TaskbarElement.CANCEL:
          this.dataUnit.cancelEdition();
          break;
        case TaskbarElement.SAVE:
          if (!this._isWaitingForSave) {
            this._isWaitingForSave = true;
            this.dataUnit.saveData().catch((err) => {
              if (err instanceof SilentException) {
                return;
              }
              else {
                throw err;
              }
            }).finally(() => {
              this._isWaitingForSave = false;
            });
          }
          break;
      }
      if (this.isEnabled(elem))
        this.actionClick.emit(elem);
    });
  }
  isEnabled(elem) {
    if (!this.isAllowed(elem)) {
      return false;
    }
    return !(this.disabledButtons && this.disabledButtons.includes(elem));
  }
  getElement(index, def) {
    const className = {
      "taskbar-element": true,
      "space-between-item": index > 0
    };
    const taskbarElement = TaskbarElement[def.toString()];
    const dataExporterStoreKey = this._element.dataset.exporterStoreKey || this.configName;
    if (taskbarElement) {
      return buildElem({
        element: def,
        className,
        dataElementId: this.getIdElemBtnNative(def),
        getTitle: elem => this.getTitle(elem),
        action: elem => this.elementClick(elem),
        isEnabled: elem => this.isEnabled(elem),
        actions: def !== TaskbarElement.CONFIGURATOR ? this.buildDynamicActionsList() : this.buildActionsSettingsList(),
        dataExporterStoreKey,
        presentationMode: this.presentationMode,
        variant: def === this.primaryButton ? "primary" : "secondary",
        size: this.sizeButtons,
      });
    }
    else {
      return buildCustomButton({
        def: def,
        className,
        dataElementId: this.getIdElemBtnCustom(def),
        action: elem => this.elementClick(elem),
        isEnabled: elem => this.isEnabled(elem),
        size: this.sizeButtons
      });
    }
  }
  buildDivider() {
    return { value: '', label: '', type: 'divider' };
  }
  buildDynamicActionsList() {
    var _a, _b;
    const customActions = [...((_a = this.customActionsList) !== null && _a !== void 0 ? _a : [])].filter(a => a !== undefined);
    const defaultActionsList = [...((_b = this.actionsList) !== null && _b !== void 0 ? _b : [])].filter(a => a !== undefined);
    if (customActions.length > 0 && defaultActionsList.length > 0) {
      customActions.push(this.buildDivider());
    }
    const combinedList = [...customActions, ...defaultActionsList];
    if (this._hiddenActionsList.length) {
      return [...combinedList, ...this._hiddenActionsList];
    }
    return combinedList;
  }
  buildActionsSettingsList() {
    return this.actionsSettingsList;
  }
  getIdElemBtnNative(taskbarElem) {
    return StringUtils.toCamelCase(taskbarElem);
  }
  getIdElemBtnCustom(btnCustom) {
    return StringUtils.toCamelCase(btnCustom.name);
  }
  isDivider(element) {
    var _a;
    if (element === undefined) {
      return false;
    }
    return (_a = element.$attrs$) === null || _a === void 0 ? void 0 : _a["data-taskbar-divider"];
  }
  removeEmpty(elements) {
    let lastElem;
    return elements.filter(elem => {
      if (elem == undefined) {
        return false;
      }
      if (this.isDivider(lastElem) && this.isDivider(elem)) {
        return false;
      }
      lastElem = elem;
      return true;
    });
  }
  appendCustomElementsInTaskbar() {
    this._customElementsId.forEach(id => {
      const elementId = id.replace(this.TASKBAR_ITEM_ID_PREFIX, '');
      const customElement = this._customElements.get(elementId);
      const container = this._element.querySelector(`#${id}`);
      if (container) {
        container === null || container === void 0 ? void 0 : container.appendChild(customElement);
      }
      else {
        this.unlinkCustomElementFromTaskbar(customElement);
      }
    });
  }
  addCustomElementContainer(elem) {
    var _a;
    const elementId = `${this.TASKBAR_ITEM_ID_PREFIX}${elem}`;
    if (!this._customElementsId.includes(elementId)) {
      this._customElementsId.push(elementId);
      (_a = this._overFlowWatcher) === null || _a === void 0 ? void 0 : _a.addNotOverFlowElement(elementId);
    }
    return h("span", { class: "ez-padding-left--medium", key: elementId, id: elementId });
  }
  getCustomElements(searchOnDocument) {
    var _a, _b;
    this._customElementsId = [];
    this._customElements = new Map();
    this._slotContainer = this.buildSlotContainer(searchOnDocument);
    const customElementsArray = Array.from((_b = (_a = this._slotContainer) === null || _a === void 0 ? void 0 : _a.children) !== null && _b !== void 0 ? _b : []);
    customElementsArray.forEach(item => this._customElements.set(item.id, item));
  }
  buildSlotContainer(searchOnDocument) {
    let slotContainer;
    if (this.customContainerId) {
      const container = document.querySelector(`#${this.customContainerId}`);
      slotContainer = container === null || container === void 0 ? void 0 : container.querySelector(`#${this.customSlotId}`);
    }
    else {
      slotContainer = this._element.querySelector(`#${this.customSlotId}`);
    }
    // Caso não encontre o slot container dentro do próprio elemento, tenta buscar na DOM do document.
    if (searchOnDocument && !slotContainer) {
      slotContainer = document.querySelector(`#${this.customSlotId}`);
    }
    return slotContainer;
  }
  handleOverFlow(overFlowingElements) {
    const elementsToHandle = overFlowingElements.filter(element => !this.hasToIgnoreOverFlow(element));
    this.resetOverFlowedElements();
    this.doOverFlowElements(elementsToHandle);
  }
  resetOverFlowedElements() {
    this._overFlowedElements.forEach(element => {
      element.classList.remove(OVERFLOWED_CLASS_NAME);
    });
    this._hiddenActionsList = [];
    this._overFlowedElements = [];
  }
  doOverFlowElements(overFlowedElements) {
    overFlowedElements.forEach(element => {
      element.classList.add(OVERFLOWED_CLASS_NAME);
      this._overFlowedElements.push(element);
      this.addItemToActionList(element);
    });
  }
  getAttributeFromName(element, attributeName) {
    var _a;
    if (!element) {
      console.warn(`[snk-taskbar] Tentativa de acessar atributo "${attributeName}" em elemento nulo.`);
      return "";
    }
    let attributeValue = element.getAttribute(attributeName);
    if (!attributeValue && ((_a = element.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'ez-tooltip') {
      const innerButton = element.querySelector('ez-button');
      if (innerButton) {
        attributeValue = innerButton.getAttribute(attributeName);
      }
    }
    return attributeValue !== null && attributeValue !== void 0 ? attributeValue : "";
  }
  addItemToActionList(element) {
    const taskbarElement = this.getAttributeFromName(element, 'data-taskbar-element');
    if (taskbarElement && this.isEnabled(taskbarElement) && this.isAllowed(taskbarElement)) {
      const optionItem = {
        value: taskbarElement,
        label: this.getAttributeFromName(element, 'data-taskbar-label'),
        iconName: this.getIconName(element)
      };
      this._hiddenActionsList.push(optionItem);
    }
  }
  getIconName(element) {
    const taskbarElement = this.getAttributeFromName(element, 'data-taskbar-element');
    if (taskbarElement === TaskbarElement.INSERT) {
      return "plus";
    }
    return this.getAttributeFromName(element, 'data-taskbar-icon');
  }
  hasToIgnoreOverFlow(element) {
    return element.classList.contains(this.TASKBAR_CUSTOM_ELEMENTS_CONTAINER_CLASS_NAME) ||
      element.classList.contains(this.TASKBAR_ADDITIONAL_SLOT_CONTAINER_CLASS_NAME);
  }
  handleOverFlowStrategy() {
    if (this.overflowStrategy === 'hiddenItems') {
      this._overFlowWatcher = new OverflowWatcher(this.buildOverFlowWatcherParams());
    }
  }
  buildOverFlowWatcherParams() {
    return {
      element: this._element,
      callback: this.handleOverFlow.bind(this),
      overFlowDirection: OverflowDirection.HORIZONTAL,
      notOverFlow: this.NOT_OVERFLOW_ELEMENTS
    };
  }
  handleDefinitions() {
    if (!this._permissions) {
      return;
    }
    this._definitions = this.elementsFromString(this.buttons);
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        var _a;
        (_a = this._overFlowWatcher) === null || _a === void 0 ? void 0 : _a.forceUpdate();
      });
    });
  }
  async getAccess() {
    if (!this._application) {
      this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    }
    if (!this._application) {
      console.warn('[snk-taskbar] Application context não encontrado. Permissões serão vazias.');
      this._permissions = {};
      return;
    }
    try {
      this._permissions = await this._application.getAllAccess(this.resourceID);
    }
    catch (error) {
      console.error('[snk-taskbar] Erro ao obter permissões:', error);
      this._permissions = {};
    }
  }
  unlinkAllCustomElements() {
    var _a;
    (_a = this._customElementsId) === null || _a === void 0 ? void 0 : _a.forEach(id => {
      const elementId = id.replace(this.TASKBAR_ITEM_ID_PREFIX, '');
      const customElement = this._customElements.get(elementId);
      this.unlinkCustomElementFromTaskbar(customElement);
    });
  }
  unlinkCustomElementFromTaskbar(customElement) {
    this._slotContainer.appendChild(customElement);
  }
  getHostClasses() {
    if (this.overflowStrategy !== 'hiddenItems')
      return 'no-wrap';
    return `full-width ${this.alignRigth ? 'align-right' : ""}`;
  }
  connectedCallback() {
    this.initializeDataUnit();
    this.handleOverFlowStrategy();
    this.getCustomElements();
  }
  async componentWillLoad() {
    this._isLoading = true;
    try {
      await this.getAccess();
      this.handleDefinitions();
    }
    catch (error) {
      console.error('[snk-taskbar] Erro ao obter permissões de acesso:', error);
    }
    finally {
      this._isLoading = false;
    }
  }
  componentDidRender() {
    this.appendCustomElementsInTaskbar();
  }
  disconnectedCallback() {
    var _a, _b;
    (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.unsubscribe(this.onSaveEvent);
    this.unlinkAllCustomElements();
    (_b = this._overFlowWatcher) === null || _b === void 0 ? void 0 : _b.destroy();
  }
  renderTaskbarElement(elem, index) {
    var _a, _b;
    if (TaskbarElement[elem]) {
      return this.getElement(index, TaskbarElement[elem]);
    }
    if ((_a = this.customButtons) === null || _a === void 0 ? void 0 : _a.has(elem)) {
      return this.getElement(index, this.customButtons.get(elem));
    }
    if (this._customElements.has(elem)) {
      return this.addCustomElementContainer(elem);
    }
    (_b = this._overFlowWatcher) === null || _b === void 0 ? void 0 : _b.addNotOverFlowElement(elem);
    return h("slot", { name: elem });
  }
  renderElements() {
    var _a, _b;
    const spacerIndex = (_a = this._definitions) === null || _a === void 0 ? void 0 : _a.indexOf(TaskbarElement.SPACER);
    const hasSpacerElement = spacerIndex !== undefined && spacerIndex !== -1;
    if (!hasSpacerElement) {
      const arrayOfElements = (_b = this._definitions) === null || _b === void 0 ? void 0 : _b.map((elem, index) => this.renderTaskbarElement(elem, index));
      return this.removeEmpty(arrayOfElements);
    }
    // Split elements into before and after spacer
    const elementsBeforeSpacer = this._definitions.slice(0, spacerIndex);
    const elementsAfterSpacer = this._definitions.slice(spacerIndex + 1);
    const beforeElements = elementsBeforeSpacer.map((elem, index) => this.renderTaskbarElement(elem, index));
    const afterElements = elementsAfterSpacer.map((elem, index) => this.renderTaskbarElement(elem, index + spacerIndex + 1));
    return [
      h("div", { class: "taskbar-group taskbar-group--start" }, this.removeEmpty(beforeElements)),
      h("div", { class: "taskbar-group taskbar-group--end" }, this.removeEmpty(afterElements))
    ];
  }
  render() {
    var _a, _b;
    if (!this._definitions) {
      return;
    }
    if (this._isLoading && !this.disableSkeleton) {
      return (h(Host, { class: this.getHostClasses() }, h("snk-taskbar-skeleton", null)));
    }
    return (h(Host, { class: this.getHostClasses() }, this.renderElements(), h("div", { id: this.TASKBAR_CUSTOM_ELEMENTS, class: this.TASKBAR_CUSTOM_ELEMENTS_CONTAINER_CLASS_NAME }, h("slot", { name: this.customSlotId }), (_a = this._overFlowWatcher) === null || _a === void 0 ? void 0 :
      _a.addNotOverFlowElement(this.TASKBAR_CUSTOM_ELEMENTS)), h("div", { id: this.TASKBAR_ADDITIONAL_SLOT, class: this.TASKBAR_ADDITIONAL_SLOT_CONTAINER_CLASS_NAME }, h("slot", { name: this.additionalSlotId }), (_b = this._overFlowWatcher) === null || _b === void 0 ? void 0 :
      _b.addNotOverFlowElement(this.TASKBAR_ADDITIONAL_SLOT))));
  }
  get _element() { return this; }
  static get watchers() { return {
    "buttons": ["observeButtons"],
    "disabledButtons": ["observeDisabledButtons"],
    "_isWaitingForSave": ["observeIsWaitingForSave"],
    "dataUnit": ["observeDataUnit"]
  }; }
  static get style() { return snkTaskbarCss; }
}, [6, "snk-taskbar", {
    "alignRigth": [4, "align-rigth"],
    "customSlotId": [1, "custom-slot-id"],
    "additionalSlotId": [1, "additional-slot-id"],
    "customContainerId": [1, "custom-container-id"],
    "overflowStrategy": [1, "overflow-strategy"],
    "configName": [1, "config-name"],
    "resourceID": [1, "resource-i-d"],
    "buttons": [1],
    "customButtons": [16],
    "actionsList": [16],
    "actionsSettingsList": [16],
    "customActionsList": [16],
    "primaryButton": [1, "primary-button"],
    "disabledButtons": [16],
    "dataUnit": [16],
    "presentationMode": [1537, "presentation-mode"],
    "messagesBuilder": [1040],
    "disableSkeleton": [4, "disable-skeleton"],
    "sizeButtons": [1, "size-buttons"],
    "_hiddenActionsList": [32],
    "_isWaitingForSave": [32],
    "_isLoading": [32]
  }, [[8, "snkCustomSlotElementsLoaded", "handleCustomSlotElementsLoaded"], [8, "taskbarSaveLocker", "handleTaskbarSaveLocker"], [8, "taskbarSaveUnlocker", "handleTaskbarSaveUnlocker"]]]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-taskbar", "snk-actions-button", "snk-data-exporter", "snk-exporter-email-sender", "snk-taskbar-skeleton", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-taskbar":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkTaskbar);
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-data-exporter":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "snk-taskbar-skeleton":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "taskbar-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
    case "taskbar-split-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}

export { SnkTaskbar as S, TaskbarElement as T, defineCustomElement as d };
