'use strict';

require('./DataFetcher-b3a8075d.js');
require('./ISave-4674c283.js');
require('@sankhyalabs/core');
const index = require('./index-e3e39724.js');
require('@sankhyalabs/ezui/dist/collection/utils/constants');
require('@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata');
require('./dataunit-fetcher-bcbc38c0.js');
require('./filter-item-type.enum-a7ffdaa6.js');
require('./form-config-fetcher-858d6407.js');
const constants = require('./constants-6d82e405.js');
const taskbarElements = require('./taskbar-elements-80eddec8.js');

class SimpleTaskbarProcessor {
  /**
   * Cria uma nova instância do processador de taskbar.
   * @param defaultButtons - Array com os botões padrão a serem exibidos
  */
  constructor(defaultButtons) {
    this._defaultButtons = [];
    this._defaultButtons = [...defaultButtons];
  }
  /**
   * Processa a taskbar aplicando regras de visibilidade e habilitação.
   * @param taskbarID - Identificador único da taskbar
   * @param taskbarManager - Gerenciador de taskbar com regras customizadas
   * @param dataState - Estado atual dos dados
   * @param disabledButtons - Array de botões desabilitados
   * @param invisibleButtons - Array de botões invisíveis
 */
  process(taskbarID, taskbarManager, dataState, disabledButtons = [], invisibleButtons = []) {
    var _a;
    this.taskbarID = taskbarID;
    this.customButtons = new Map();
    this.buttonsArray = [];
    this.disabledButtons = [...disabledButtons];
    (_a = this.getButtonsArray(taskbarManager, dataState)) === null || _a === void 0 ? void 0 : _a.forEach((btnDef) => {
      let buttonName;
      if (typeof btnDef === "string") {
        buttonName = btnDef;
      }
      else {
        this.customButtons.set(btnDef.name, btnDef);
        buttonName = btnDef.name;
      }
      if (!invisibleButtons.includes(buttonName)) {
        if (!this.isEnabled(taskbarManager, buttonName, dataState, disabledButtons)) {
          this.disabledButtons.push(buttonName);
        }
        this.buttonsArray.push(buttonName);
      }
    });
    this.buttons = this.buttonsArray.join(",");
  }
  getButtonsArray(taskbarManager, dataState) {
    if (taskbarManager) {
      return taskbarManager.getButtons(this.taskbarID, dataState, [...this._defaultButtons]);
    }
    return this._defaultButtons;
  }
  isEnabled(taskbarManager, buttonName, dataState, disabled) {
    const originalValue = !disabled.includes(buttonName);
    if (taskbarManager && taskbarManager.isEnabled) {
      return taskbarManager.isEnabled(this.taskbarID, dataState, buttonName, originalValue);
    }
    return originalValue;
  }
}

const DEFAULT_TASKBAR_BUTTONS = [
  taskbarElements.TaskbarElement.FORM_MODE,
  taskbarElements.TaskbarElement.PREVIOUS,
  taskbarElements.TaskbarElement.NEXT,
  taskbarElements.TaskbarElement.REFRESH,
  taskbarElements.TaskbarElement.SPACER,
  taskbarElements.TaskbarElement.ACTIONS_BUTTON,
  taskbarElements.TaskbarElement.DATA_EXPORTER,
  taskbarElements.TaskbarElement.ATTACH,
  taskbarElements.TaskbarElement.CLONE,
  taskbarElements.TaskbarElement.UPDATE,
  taskbarElements.TaskbarElement.REMOVE,
  taskbarElements.TaskbarElement.INSERT,
  taskbarElements.TaskbarElement.CONFIGURATOR,
  taskbarElements.TaskbarElement.MORE_OPTIONS,
];
exports.CustomTaskbarButton = void 0;
(function (CustomTaskbarButton) {
  CustomTaskbarButton["FILTER"] = "FILTER";
  CustomTaskbarButton["ENTITY_SEARCH"] = "ENTITY_SEARCH";
})(exports.CustomTaskbarButton || (exports.CustomTaskbarButton = {}));
/**
 * Insere os botões customizados à esquerda do elemento SPACER na lista de botões.
 * Caso o SPACER não seja encontrado, os botões são inseridos no início da lista.
 */
function insertCustomButtonsBeforeSpacer(buttons, customButtons) {
  const spacerIndex = buttons.findIndex(btn => btn === taskbarElements.TaskbarElement.SPACER || (typeof btn === 'string' && btn === 'SPACER'));
  if (spacerIndex > -1) {
    return [
      ...buttons.slice(0, spacerIndex),
      ...customButtons,
      ...buttons.slice(spacerIndex),
    ];
  }
  return [...customButtons, ...buttons];
}
function buildNavigationDisabledBtns(dataState) {
  const navigationDisabled = [];
  if (!(dataState === null || dataState === void 0 ? void 0 : dataState.hasPrevious)) {
    navigationDisabled.push(taskbarElements.TaskbarElement.PREVIOUS);
  }
  if (!(dataState === null || dataState === void 0 ? void 0 : dataState.hasNext)) {
    navigationDisabled.push(taskbarElements.TaskbarElement.NEXT);
  }
  return navigationDisabled;
}
function buildNativeTaskbarManager(currentViewMode, mergeTaskbarManager, messagesBuilder) {
  var _a, _b;
  const CUSTOM_BUTTONS = [
    {
      name: exports.CustomTaskbarButton.FILTER,
      hint: (_a = messagesBuilder === null || messagesBuilder === void 0 ? void 0 : messagesBuilder.getMessage("snkCrud.customButtons.filter")) !== null && _a !== void 0 ? _a : "Abre o painel de filtros",
      iconName: "filter",
    },
    {
      name: exports.CustomTaskbarButton.ENTITY_SEARCH,
      hint: (_b = messagesBuilder === null || messagesBuilder === void 0 ? void 0 : messagesBuilder.getMessage("snkCrud.customButtons.entitySearch")) !== null && _b !== void 0 ? _b : "Busca na entidade",
      iconName: "search",
    },
  ];
  const EDITION_MODE_BUTTONS = [
    taskbarElements.TaskbarElement.CANCEL,
    taskbarElements.TaskbarElement.SAVE,
  ];
  return {
    getButtons: (taskbarID, dataState, defaultButtons) => {
      var _a, _b;
      if (!taskbarID) {
        console.warn('taskbarID não fornecido');
        return [];
      }
      const isInEditionMode = (dataState === null || dataState === void 0 ? void 0 : dataState.insertionMode) || (dataState === null || dataState === void 0 ? void 0 : dataState.isDirty);
      if (isInEditionMode) {
        return EDITION_MODE_BUTTONS;
      }
      if (currentViewMode === constants.VIEW_MODE.FORM) {
        const indexFormMode = defaultButtons.indexOf(taskbarElements.TaskbarElement.FORM_MODE);
        if (indexFormMode > -1) {
          defaultButtons = [
            ...defaultButtons.slice(0, indexFormMode),
            taskbarElements.TaskbarElement.GRID_MODE,
            ...defaultButtons.slice(indexFormMode + 1)
          ];
        }
      }
      if (((_b = (_a = dataState === null || dataState === void 0 ? void 0 : dataState.selectionInfo) === null || _a === void 0 ? void 0 : _a.records) === null || _b === void 0 ? void 0 : _b.length) > 1) {
        const indexUpdate = defaultButtons.indexOf(taskbarElements.TaskbarElement.UPDATE);
        if (indexUpdate > -1) {
          defaultButtons = [
            ...defaultButtons.slice(0, indexUpdate),
            taskbarElements.TaskbarElement.UPDATE_MULTIPLE,
            ...defaultButtons.slice(indexUpdate + 1)
          ];
        }
      }
      const defaultsWithCustomButtons = insertCustomButtonsBeforeSpacer(defaultButtons, CUSTOM_BUTTONS);
      if (mergeTaskbarManager === null || mergeTaskbarManager === void 0 ? void 0 : mergeTaskbarManager.getButtons) {
        return mergeTaskbarManager.getButtons(taskbarID, dataState, defaultsWithCustomButtons);
      }
      return defaultsWithCustomButtons;
    },
    isEnabled: (_, dataState, buttonName, originalValue) => {
      var _a;
      if (!dataState) {
        return originalValue;
      }
      const hasSelectedRecord = dataState.selectedRecord !== undefined;
      const buttonsRequiringSelection = [
        taskbarElements.TaskbarElement.UPDATE,
        taskbarElements.TaskbarElement.REMOVE,
        taskbarElements.TaskbarElement.ATTACH,
        taskbarElements.TaskbarElement.CLONE,
      ];
      if (!hasSelectedRecord && buttonsRequiringSelection.includes(buttonName)) {
        return false;
      }
      const navigationDisabled = buildNavigationDisabledBtns(dataState);
      if (navigationDisabled.includes(buttonName)) {
        return false;
      }
      return (_a = mergeTaskbarManager === null || mergeTaskbarManager === void 0 ? void 0 : mergeTaskbarManager.isEnabled(_, dataState, buttonName, originalValue)) !== null && _a !== void 0 ? _a : originalValue;
    },
    getMoreOptions(taskbarId, configName, dataState, currentActions) {
      var _a;
      return (_a = mergeTaskbarManager === null || mergeTaskbarManager === void 0 ? void 0 : mergeTaskbarManager.getMoreOptions) === null || _a === void 0 ? void 0 : _a.call(mergeTaskbarManager, taskbarId, configName, dataState, currentActions);
    },
  };
}
function getHeaderTaskbarId(dataState, presentationMode) {
  var _a;
  const hasSelectedRecord = dataState && !!((_a = dataState.selectionInfo) === null || _a === void 0 ? void 0 : _a.length);
  const taskbarIdPrefixLookup = {
    primary: "snkGridHeaderTaskbar",
    secondary: "snkGridHeaderTaskbar",
    singleTaskbar: "snkGridHeaderTaskbar.singleTaskbar",
  };
  const taskbarIdPrefix = taskbarIdPrefixLookup[presentationMode];
  let headerTaskbarId = hasSelectedRecord ? `${taskbarIdPrefix}.selected` : `${taskbarIdPrefix}.unselected`;
  if ((dataState === null || dataState === void 0 ? void 0 : dataState.isDirty) && presentationMode === index.PresentationMode.SINGLE_TASKBAR) {
    headerTaskbarId = "snkGridHeaderTaskbar.singleTaskbar.finish_edition";
  }
  return headerTaskbarId;
}
function getTopTaskBarId(dataState, presentationMode) {
  const suffixLookup = {
    primary: '',
    secondary: '.secondary',
    singleTaskbar: '.singleTaskbar',
  };
  const sufix = suffixLookup[presentationMode];
  if (dataState === null || dataState === void 0 ? void 0 : dataState.isDirty) {
    return `snkGridTopTaskbar.finish_edition${sufix}`;
  }
  return `snkGridTopTaskbar.regular${sufix}`;
}

exports.DEFAULT_TASKBAR_BUTTONS = DEFAULT_TASKBAR_BUTTONS;
exports.SimpleTaskbarProcessor = SimpleTaskbarProcessor;
exports.buildNativeTaskbarManager = buildNativeTaskbarManager;
exports.getHeaderTaskbarId = getHeaderTaskbarId;
exports.getTopTaskBarId = getTopTaskBarId;
