import { r as registerInstance, e as createEvent, h, f as Host, g as getElement } from './index-e9c7ceaa.js';
import { Action, ElementIDUtils, LockManager, LockManagerOperation, SilentException, StringUtils, ApplicationContext, OVERFLOWED_CLASS_NAME, OverflowWatcher, OverflowDirection } from '@sankhyalabs/core';
import { P as PresentationMode } from './index-b40568ff.js';
import { A as AuthorizationConfig } from './AuthorizationConfig-dcbd207a.js';
import { T as TaskbarElement, V as VisibleWhenForbidden, A as AuthorizationElements, b as buildElem, a as buildCustomButton } from './taskbar-elements-b3c5a3ce.js';
import './index-c961465b.js';

const snkTaskbarCss = ".sc-snk-taskbar-h{display:flex;flex-wrap:wrap}.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}";

const SnkTaskbar = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    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.ACTIONS_BUTTON_TAG = 'TASKBAR-ACTIONS-BUTTON';
    this.NOT_OVERFLOW_ELEMENTS = ["moreOptions", "dataExporter_snkDataExporter", "actionsButton_snkActionsButton"];
    this.TASKBAR_CUSTOM_ELEMENTS = 'taskbar-custom-elements-container';
    this._dataUnitInitialized = false;
    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._permissions = undefined;
    this._overFlowedElements = [];
    this._customElements = undefined;
    this._customElementsId = undefined;
    this._slotContainer = undefined;
    this._hiddenActionsList = [];
    this._lastWidth = undefined;
    this._hasToUpdateOverFlow = false;
    this._isWaitingForSave = false;
    this.alignRigth = false;
    this.customSlotId = "TASKBAR_CUSTOM_ELEMENTS";
    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.primaryButton = undefined;
    this.disabledButtons = undefined;
    this.dataUnit = undefined;
    this.presentationMode = PresentationMode.PRIMARY;
    this.messagesBuilder = undefined;
  }
  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._definitions = undefined;
    requestAnimationFrame(() => {
      requestAnimationFrame(() => { var _a; return (_a = this._overFlowWatcher) === null || _a === void 0 ? void 0 : _a.forceUpdate(); });
    });
  }
  observeDisabledButtons() {
    var _a;
    (_a = this._overFlowWatcher) === null || _a === void 0 ? void 0 : _a.forceUpdate();
  }
  observeLastWidth(newValue, oldValue) {
    if (oldValue === 0 && newValue !== 0) {
      this._hasToUpdateOverFlow = true;
    }
  }
  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) {
    if (!!dataUnit && !this._dataUnitInitialized) {
      this._dataUnitInitialized = true;
      const dataInfo = { dataUnit: this.dataUnit };
      ElementIDUtils.addIDInfo(this._element, null, dataInfo);
      this.dataUnit.subscribe(this.onSaveEvent);
    }
  }
  // Internal methods
  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 (buttonName === AuthorizationElements.CONFIGURATOR) {
      return this._permissions
        ? this._permissions.isSup
          || this._permissions[AuthorizationConfig.CONFIG_GRID]
          || this._permissions[AuthorizationConfig.CONFIG]
        : false;
    }
    if (AuthorizationElements[buttonName]) {
      return this._permissions ? this._permissions.isSup || this._permissions[buttonName] : false;
    }
    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));
  }
  validatePresentationMode() {
    if (Object.values(PresentationMode).includes(this.presentationMode)) {
      return;
    }
    this.presentationMode = PresentationMode.PRIMARY;
  }
  getElement(index, def) {
    let className = def === this.primaryButton ? "ez-button--primary " : "";
    if (index > 1) {
      className += "ez-padding-left--medium";
    }
    const taskbarElement = TaskbarElement[def.toString()];
    const dataExporterStoreKey = this._element.dataset.exporterStoreKey || this.configName;
    if (taskbarElement) {
      return buildElem(def, className, this.getIdElemBtnNative(def), elem => this.getTitle(elem), elem => this.elementClick(elem), elem => this.isEnabled(elem), def !== TaskbarElement.CONFIGURATOR ? this.buildDynamicActionsList() : this.buildActionsSettingsList(), dataExporterStoreKey, this.presentationMode);
    }
    else {
      return buildCustomButton(def, className, this.getIdElemBtnCustom(def), elem => this.elementClick(elem), elem => this.isEnabled(elem));
    }
  }
  buildDynamicActionsList() {
    var _a;
    if (this._hiddenActionsList.length) {
      return [...((_a = this.actionsList) !== null && _a !== void 0 ? _a : []), ...this._hiddenActionsList];
    }
    return this.actionsList;
  }
  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õa 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;
  }
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    if (this._application) {
      this._application.getAllAccess(this.resourceID).then(access => this._permissions = access);
    }
    else {
      this._permissions = {};
    }
    this.getCustomElements();
  }
  componentWillRender() {
    this.handleDefinitions();
    this.validatePresentationMode();
    this.updateOverFlowIfNeeded();
  }
  handleDefinitions() {
    if (this._definitions == undefined && this._permissions) {
      this._definitions = this.elementsFromString(this.buttons);
    }
  }
  updateOverFlowIfNeeded() {
    if (this._hasToUpdateOverFlow) {
      requestAnimationFrame(() => { var _a; return (_a = this._overFlowWatcher) === null || _a === void 0 ? void 0 : _a.forceUpdate(); });
      this._hasToUpdateOverFlow = false;
    }
  }
  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);
    });
  }
  addItemToActionList(element) {
    const taskbarElement = this.getTaskbarElementName(element);
    if (taskbarElement && this.isEnabled(taskbarElement) && this.isAllowed(taskbarElement)) {
      const optionItem = {
        value: taskbarElement,
        label: this.getTaskbarElementLabel(element),
        iconName: this.getTaskbarElementIcon(element)
      };
      this._hiddenActionsList.push(optionItem);
    }
  }
  getTaskbarElementName(element) {
    var _a;
    return (_a = element.getAttribute('data-taskbar-element')) !== null && _a !== void 0 ? _a : "";
  }
  getTaskbarElementIcon(element) {
    var _a;
    return (_a = element.getAttribute('data-taskbar-icon')) !== null && _a !== void 0 ? _a : "";
  }
  getTaskbarElementLabel(element) {
    var _a;
    return (_a = element.getAttribute('data-taskbar-label')) !== null && _a !== void 0 ? _a : "";
  }
  hasToIgnoreOverFlow(element) {
    return element.classList.contains(this.TASKBAR_CUSTOM_ELEMENTS_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
    };
  }
  componentDidLoad() {
    this.initializeDataUnit(this.dataUnit);
    this.handleOverFlowStrategy();
  }
  componentDidRender() {
    this.appendCustomElementsInTaskbar();
    this.updateLastWidth();
  }
  updateLastWidth() {
    this._lastWidth = this._element.getBoundingClientRect().width;
  }
  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();
  }
  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);
  }
  render() {
    var _a;
    if (this._definitions === undefined) {
      return undefined;
    }
    let index = 0;
    return (h(Host, { class: this.getHostClasses() }, this.removeEmpty(this._definitions.map((elem) => {
      var _a, _b;
      index++;
      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 });
    })), 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))));
  }
  getHostClasses() {
    if (this.overflowStrategy !== 'hiddenItems')
      return 'no-wrap';
    return `full-width ${this.alignRigth ? 'align-right' : ""}`;
  }
  get _element() { return getElement(this); }
  static get watchers() { return {
    "buttons": ["observeButtons"],
    "disabledButtons": ["observeDisabledButtons"],
    "_lastWidth": ["observeLastWidth"],
    "_isWaitingForSave": ["observeIsWaitingForSave"],
    "dataUnit": ["observeDataUnit"]
  }; }
};
SnkTaskbar.style = snkTaskbarCss;

export { SnkTaskbar as snk_taskbar };
