'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-17105557.js');
const core = require('@sankhyalabs/core');
const DataUnit = require('@sankhyalabs/core/dist/dataunit/DataUnit');
const utils = require('@sankhyalabs/ezui/dist/collection/utils');
require('./DataFetcher-21f8c2dc.js');
require('./ISave-f926fe9e.js');
const SnkMultiSelectionListDataSource = require('./SnkMultiSelectionListDataSource-decf3728.js');
const index$1 = require('./index-e3e39724.js');
require('@sankhyalabs/ezui/dist/collection/utils/constants');
require('@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata');
require('./dataunit-fetcher-6c85a04d.js');
require('./filter-item-type.enum-a7ffdaa6.js');
require('./form-config-fetcher-fef79845.js');
require('./constants-6d82e405.js');
const ConfigStorage = require('./ConfigStorage-b829def9.js');
const index$2 = require('./index-22a8223a.js');
const GetSelectedRecordsIDsInfo = require('./GetSelectedRecordsIDsInfo-bd50caf1.js');
const filterValidate = require('./filter-validate-cb4ed41a.js');
const taskbarElements = require('./taskbar-elements-f3ecbf5c.js');
const taskbarProcessor = require('./taskbar-processor-2fba34a8.js');
require('./PrintUtils-bcaeb82f.js');
require('./IFetchDataExporterParams-e78ec415.js');
require('@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource');
require('@sankhyalabs/ezui/dist/collection/components/ez-grid/utils');
require('@sankhyalabs/core/dist/utils/SortingUtils');
require('./ResourceIDUtils-5ff86aa7.js');

class ServerSideExporterProvider extends SnkMultiSelectionListDataSource.CommonsExporter {
  getFilters() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getAppliedFilters();
  }
  getOrders() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getSort();
  }
  getResourceURI() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.name;
  }
  getSelectedNumber() {
    return this.dataUnit.getSelectionInfo().length;
  }
  getTotalRecords() {
    var _a, _b, _c;
    const { total } = ((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getPaginationInfo()) || {};
    return total !== null && total !== void 0 ? total : (_c = (_b = this.dataUnit) === null || _b === void 0 ? void 0 : _b.records) === null || _c === void 0 ? void 0 : _c.length;
  }
  getSelectedIDs() {
    return GetSelectedRecordsIDsInfo.getSelectedRecordsIDsInfo(this.dataUnit);
  }
  getOffset() {
    return this.getExporterOffset(this.getPaginationInfo());
  }
  getPageSize() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.pageSize;
  }
  getExportLimit() {
    return 5000;
  }
  getRecordID() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.records) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.__record__id__;
  }
  getPaginationInfo() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getPaginationInfo();
  }
  getExporterOffset(paginationInfo) {
    if (paginationInfo == undefined) {
      return;
    }
    const offset = paginationInfo.firstRecord;
    if (offset > 0) {
      return (offset - 1);
    }
    return offset;
  }
}

const snkGridCss = ".sc-snk-grid-h{--snk-grid-min-height:300px;--snk-grid-padding:var(--space--small)}.snk-grid__container.sc-snk-grid{display:flex;height:100%;width:100%;padding:var(--snk-grid-padding);outline:none}.snk-grid__header.sc-snk-grid{width:100%;display:flex;flex-wrap:nowrap;justify-content:flex-end}.snk-grid__filter-bar.sc-snk-grid{width:100%}.snk-grid__header-divider.sc-snk-grid{margin-bottom:var(--space--medium)}.snk-grid__table.sc-snk-grid{min-height:var(--snk-grid-min-height)}.snk-grid-container__without-shadow.sc-snk-grid{--ezgrid__container--shadow:unset}.snk-grid-container__footer.sc-snk-grid{background-color:var(--background--xlight, #FFF);border-radius:0 0 var(--border--radius-medium) var(--border--radius-medium);box-shadow:var(--shadow--small)}";

const SnkGrid = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.actionClick = index.createEvent(this, "actionClick", 7);
    this.gridDoubleClick = index.createEvent(this, "gridDoubleClick", 7);
    this.componentReady = index.createEvent(this, "componentReady", 7);
    this._customEditors = new Map();
    this._customRenders = new Map();
    this._keyboardManager = new core.KeyboardManager();
    this._topTaskbarProcessor = new taskbarProcessor.TaskbarProcessor({
      'snkGridTopTaskbar.regular': ['FORM_MODE', 'CONFIGURATOR', 'INSERT'],
      'snkGridTopTaskbar.regular.secondary': ['FORM_MODE', 'CONFIGURATOR', 'INSERT'],
      'snkGridTopTaskbar.regular.singleTaskbar': [],
      'snkGridTopTaskbar.finish_edition': ['CANCEL', 'SAVE', this.handleAddFormMode()],
      'snkGridTopTaskbar.finish_edition.secondary': [],
      'snkGridTopTaskbar.finish_edition.singleTaskbar': [],
    });
    this._headerTaskbarProcessor = new taskbarProcessor.TaskbarProcessor({
      'snkGridHeaderTaskbar.unselected': ['REFRESH', 'DATA_EXPORTER', 'ACTIONS_BUTTON', 'MORE_OPTIONS'],
      'snkGridHeaderTaskbar.selected': this.getGridHeaderSelectedBtns(),
      'snkGridHeaderTaskbar.detail.unselected': ['REFRESH', 'ACTIONS_BUTTON', 'MORE_OPTIONS'],
      'snkGridHeaderTaskbar.detail.selected': ['UPDATE', 'ATTACH', 'CLONE', 'REMOVE', 'MORE_OPTIONS', 'DIVIDER', 'REFRESH', 'ACTIONS_BUTTON'],
      'snkGridHeaderTaskbar.singleTaskbar.unselected': ['INSERT', 'FORM_MODE', 'CONFIGURATOR', 'REFRESH', 'DATA_EXPORTER', 'ACTIONS_BUTTON', 'MORE_OPTIONS'],
      'snkGridHeaderTaskbar.singleTaskbar.selected': ['UPDATE', 'CLONE', 'REMOVE', 'MORE_OPTIONS', 'DIVIDER', 'ATTACH', 'FORM_MODE', 'CONFIGURATOR', 'REFRESH', 'DATA_EXPORTER', 'ACTIONS_BUTTON'],
      'snkGridHeaderTaskbar.singleTaskbar.detail.unselected': ['INSERT', 'FORM_MODE', 'CONFIGURATOR', 'REFRESH', 'ACTIONS_BUTTON', 'MORE_OPTIONS'],
      'snkGridHeaderTaskbar.singleTaskbar.detail.selected': ['UPDATE', 'ATTACH', 'CLONE', 'REMOVE', 'MORE_OPTIONS', 'DIVIDER', 'FORM_MODE', 'CONFIGURATOR', 'REFRESH', 'ACTIONS_BUTTON'],
      'snkGridHeaderTaskbar.singleTaskbar.finish_edition': ['CANCEL', 'SAVE', this.handleAddFormMode()],
    });
    this.dataUnitInterceptor = {
      interceptAction: async (action) => {
        if (action.type === core.Action.METADATA_LOADED) {
          return await this.interceptMetadataLoaded(action);
        }
        if (action.type === core.Action.LOADING_DATA) {
          return await this.interceptLoadData(action);
        }
        return action;
      },
    };
    this._dataUnit = undefined;
    this._dataState = undefined;
    this._gridConfig = undefined;
    this._popUpGridConfig = false;
    this._showSnkFilterBar = true;
    this._enableContinuousInsert = false;
    this.columnFilterDataSource = new SnkMultiSelectionListDataSource.SnkMultiSelectionListDataSource();
    this.enableLockManagerLoadingComp = false;
    this.enableLockManagerTaskbarClick = false;
    this.configName = undefined;
    this.filterBarTitle = undefined;
    this.resourceID = undefined;
    this.selectionToastConfig = undefined;
    this.actionsList = undefined;
    this.isDetail = undefined;
    this.taskbarManager = undefined;
    this.statusResolver = undefined;
    this.multipleSelection = undefined;
    this.presentationMode = index$1.PresentationMode.PRIMARY;
    this.messagesBuilder = undefined;
    this.useEnterLikeTab = false;
    this.recordsValidator = undefined;
    this.canEdit = true;
    this.taskbarCustomContainerId = undefined;
    this.gridHeaderCustomSlotId = 'GRID_HEADER_CUSTOM_ELEMENTS';
    this.topTaskbarCustomSlotId = 'GRID_TASKBAR_CUSTOM_ELEMENTS';
    this.disablePersonalizedFilter = undefined;
    this.gridLegacyConfigName = undefined;
    this.filterBarLegacyConfigName = undefined;
    this.autoLoad = undefined;
    this.autoFocus = true;
    this.enableGridInsert = false;
    this.outlineMode = false;
    this.suppressHorizontalScroll = false;
    this.strategyExporter = index$1.ExporterStrategy.SERVER_SIDE;
    this.useSearchColumn = true;
    this.multipleEditionEnabled = true;
    this.paginationCounterMode = 'auto';
    this.suppressCheckboxColumn = undefined;
    this.suppressFilterColumn = false;
    this.compact = undefined;
    this.filterCustomConfig = undefined;
    this.filterCustomConfigInterceptor = undefined;
  }
  getGridHeaderSelectedBtns() {
    const btns = [
      taskbarElements.TaskbarElement.UPDATE, taskbarElements.TaskbarElement.CLONE, taskbarElements.TaskbarElement.REMOVE,
      taskbarElements.TaskbarElement.MORE_OPTIONS, taskbarElements.TaskbarElement.DIVIDER, taskbarElements.TaskbarElement.ATTACH, taskbarElements.TaskbarElement.FORM_MODE,
      taskbarElements.TaskbarElement.CONFIGURATOR, taskbarElements.TaskbarElement.REFRESH, taskbarElements.TaskbarElement.DATA_EXPORTER, taskbarElements.TaskbarElement.ACTIONS_BUTTON,
    ];
    if (this.multipleEditionEnabled)
      btns.unshift(taskbarElements.TaskbarElement.UPDATE_MULTIPLE);
    return btns;
  }
  async refreshColumnFilterDataSource() {
    await this._grid.refreshColumnFilterDataSource();
  }
  /**
   * Recarrega a configuração da grade.
   * @description Este método força o recarregamento da configuração da grade a partir do `ConfigStorage`. A operação é assíncrona, mas o método não aguarda sua conclusão.
   */
  reloadConfig() {
    this.loadConfig();
  }
  /**
   * Exibe a janela de configurações da grade.
   * @async
   * @description Este método abre o pop-up de configuração de colunas da grade, permitindo ao usuário ajustar a visibilidade, ordem e largura das colunas.
   * @returns {Promise<void>} Uma promessa que é resolvida quando a janela de configuração é exibida.
   */
  async showConfig() {
    if (this._grid == undefined) {
      return;
    }
    this.openGridConfig();
  }
  /**
   * Fecha a janela de configurações da grade.
   * @async
   * @description Este método fecha o pop-up de configuração de colunas da grade.
   * @returns {Promise<void>} Uma promessa que é resolvida quando a janela de configuração é fechada.
   */
  async hideConfig() {
    if (this._grid == undefined) {
      return;
    }
    this.closeGridConfig();
  }
  /**
   * Define a configuração da grade.
   * @async
   * @description Aplica uma nova configuração de colunas e ordenação à grade.
   * @param {IGridConfig} config O objeto de configuração a ser aplicado na grade.
   * @returns {Promise<void>} Uma promessa que é resolvida quando a configuração é aplicada.
   */
  async setConfig(config) {
    this.setGridConfig(config);
  }
  /**
   * Recarrega a barra de filtros da grade, buscando o estado do servidor.
   * @async
   * @description Força o recarregamento da barra de filtros, atualizando suas configurações e filtros a partir do servidor.
   * @returns {Promise<void>} Uma promessa que é resolvida quando a barra de filtros é recarregada.
   */
  async reloadFilterBar() {
    var _a;
    (_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.reload();
  }
  /**
   * Retorna o elemento da barra de filtros da grade.
   * @async
   * @description Este método permite acessar o elemento da barra de filtros, que pode ser útil para manipulações adicionais ou para obter o estado atual dos filtros aplicados.
   * @returns {Promise<HTMLSnkFilterBarElement>} O elemento da barra de filtros.
   */
  async getFilterBar() {
    return this._snkFilterBar;
  }
  /**
   * Registra um editor customizado para um campo da grade ou formulário.
   * @async
   * @description Adiciona um componente de edição personalizado para um campo específico. Este editor será usado tanto na edição em linha na grade quanto em formulários de detalhe.
   * @param {string} fieldName O nome do campo que receberá o editor customizado.
   * @param {ICustomEditor} customEditor A instância do editor customizado.
   * @param {string} [detailContext] O contexto de detalhe onde o editor será aplicado (opcional).
   * @returns {Promise<void>} Uma promessa que é resolvida quando o editor é registrado.
   */
  async addCustomEditor(fieldName, customEditor, detailContext) {
    if (this._grid) {
      this._grid.addCustomEditor(fieldName, customEditor, detailContext);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, { customEditor, detailContext });
    this._customEditors = newCustomEditors;
  }
  /**
   * Registra um renderizador customizado para uma coluna da grade.
   * @async
   * @description Adiciona um componente de renderização personalizado para uma coluna específica, permitindo a exibição de conteúdo customizado nas células.
   * @param {string} fieldName O nome do campo (coluna) que receberá o renderizador customizado.
   * @param {ICustomRender} customRender A instância do renderizador customizado.
   * @param {string} [detailContext] O contexto de detalhe onde o renderizador será aplicado (opcional).
   * @returns {Promise<void>} Uma promessa que é resolvida quando o renderizador é registrado.
   */
  async addGridCustomRender(fieldName, customRender, detailContext) {
    if (this._grid) {
      this._grid.addGridCustomRender(fieldName, customRender, detailContext);
      return;
    }
    const newCustomRenders = new Map(this._customRenders);
    newCustomRenders.set(fieldName, { customRender, detailContext });
    this._customRenders = newCustomRenders;
  }
  /**
   * Registra um formatador de valor customizado para uma coluna da grade.
   * @async
   * @description Adiciona uma função de formatação personalizada para os valores de uma coluna específica, afetando como os dados são exibidos.
   * @param {string} columnName O nome da coluna que receberá o formatador.
   * @param {ICustomFormatter} customFormatter A instância do formatador de valor.
   * @returns {Promise<void>} Uma promessa que é resolvida quando o formatador é registrado.
   */
  async addCustomValueFormatter(columnName, customFormatter) {
    this._grid.addCustomValueFormatter(columnName, customFormatter);
  }
  /**
   * Remove um formatador de valor customizado de uma coluna da grade.
   * @async
   * @description Remove uma função de formatação personalizada previamente registrada para uma coluna.
   * @param {string} columnName O nome da coluna da qual o formatador será removido.
   * @returns {Promise<void>} Uma promessa que é resolvida quando o formatador é removido.
   */
  async removeCustomValueFormatter(columnName) {
    this._grid.removeCustomValueFormatter(columnName);
  }
  /**
   * Atribui o foco para a grade.
   * @async
   * @description Move o foco do navegador para o componente da grade, permitindo a navegação por teclado.
   * @returns {Promise<void>} Uma promessa que é resolvida quando o foco é atribuído.
   */
  async setFocus() {
    this._grid.setFocus();
  }
  async handleClick(event) {
    var _a;
    if (this.hasToBlockEvent(event)) {
      event.preventDefault();
      event.stopPropagation();
      if (!await this._dataUnit.cancelEdition())
        return;
      const newEvent = new event.constructor(event.type, event);
      (_a = event.target) === null || _a === void 0 ? void 0 : _a.dispatchEvent(newEvent);
    }
    if (this._grid && !this._grid.contains(event.target)) {
      this._grid.stopEdit();
    }
  }
  hasToBlockEvent(event) {
    var _a;
    return ((_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.contains(event.target)) && this.enableGridInsert && this._dataUnit.hasNewRecord();
  }
  async handleGridLegacyConfigName(newLegacyConfig, oldLegacyConfig) {
    if (!newLegacyConfig) {
      return;
    }
    if (newLegacyConfig === oldLegacyConfig) {
      return;
    }
    this.addGridLegacyConfigName();
    this.loadConfig();
  }
  handleAddFormMode() {
    return this.enableGridInsert ? taskbarElements.TaskbarElement.FORM_MODE : '';
  }
  openGridConfig() {
    this._grid.getColumnsState()
      .then((gridColumns) => {
      this._snkGridConfig.columns = gridColumns.filter(c => c.name);
      this._popUpGridConfig = true;
    });
  }
  closeGridConfig() {
    this._popUpGridConfig = false;
  }
  setGridConfig(config) {
    this._gridConfig = config;
    SnkMultiSelectionListDataSource.CrudUtils.assertDefaultSorting(this._gridConfig, this._dataUnit);
  }
  fixColumNameCharset(columnName) {
    try {
      return decodeURIComponent(escape(columnName));
    }
    catch (e) {
      return columnName;
    }
  }
  normalizeGridConfig(config) {
    if (!config)
      return config;
    const columnsMapped = config.columns.map(column => (Object.assign(Object.assign({}, column), { name: this.fixColumNameCharset(column.name) })));
    return Object.assign(Object.assign({}, config), { columns: columnsMapped });
  }
  loadConfig() {
    ConfigStorage.ConfigStorage.loadGridConfig(this.configName, this.resourceID)
      .then((config) => {
      this.setGridConfig(this.normalizeGridConfig(config));
    })
      .catch((error) => {
      console.warn(error);
    });
  }
  addGridLegacyConfigName() {
    if (this.gridLegacyConfigName && this.configName) {
      ConfigStorage.ConfigStorage.addGridLegacyConfig(this.configName, this.gridLegacyConfigName);
    }
  }
  hasCalculatedFields(columnNames) {
    let hasCalculatedFields = false;
    columnNames.forEach(name => {
      var _a;
      const field = this._dataUnit.getField(name);
      if (((_a = field.properties) === null || _a === void 0 ? void 0 : _a.calculated) === 'true') {
        hasCalculatedFields = true;
      }
    });
    return hasCalculatedFields;
  }
  gridConfigChangeHandler(evt) {
    const config = this.normalizeGridConfig(evt.detail);
    ConfigStorage.ConfigStorage.saveGridConfig(config, this.configName, this.resourceID);
    evt.stopPropagation();
  }
  modalConfigChangeHandler(evt) {
    const config = this.normalizeGridConfig(evt.detail);
    this._grid.setColumnsState(config.columns)
      .then(() => {
      this.setGridConfig(config);
      this.closeGridConfig();
      this.dataExporterProviderStore();
    });
    evt.stopPropagation();
  }
  async hasToForceClientSideExporter() {
    if (!this._grid) {
      return false;
    }
    const filters = await this._grid.getAppliedColumnFilters();
    const columnNames = filters.map(filter => filter.name.replace('FILTRO_COLUNA_', ''));
    return this.hasCalculatedFields(columnNames);
  }
  async dataExporterProviderStore() {
    /**
     * O ServerSideExporterProvider do SankhyaOm não suporta a filtragem de campos calculados.
     * Por esse motivo, precisamos verificar os filtros aplicados no momento e recriar o dataExporterProvider conforme necessário.
     * Se houver campos calculados, forçamos o uso do clientSide, caso contrário é seguido o fluxo padrão.
     */
    const forceClientSide = await this.hasToForceClientSideExporter();
    const dataExporterProvider = (forceClientSide || this.strategyExporter === index$1.ExporterStrategy.CLIENT_SIDE)
      ? new SnkMultiSelectionListDataSource.ClientSideExporterProvider(this._dataUnit, this._grid)
      : new ServerSideExporterProvider(this._dataUnit, this._grid);
    index$2.store.set('exporterProviders', Object.assign(Object.assign({}, index$2.store.get('exporterProviders')), { [this.configName]: dataExporterProvider }));
  }
  addElementID() {
    const dataInfo = { dataUnit: this._dataUnit };
    core.ElementIDUtils.addIDInfo(this._element, null, dataInfo);
  }
  loadGridCustomFormatters(fields) {
    if (!fields || !this._grid) {
      return;
    }
    fields.forEach((field) => {
      var _a;
      if ((_a = field.properties) === null || _a === void 0 ? void 0 : _a.rm_precision) {
        this.addCustomValueFormatter(field.name, this._rmPrecisionCustomValueFormatter);
      }
    });
  }
  async interceptMetadataLoaded(action) {
    this.loadGridCustomFormatters(action.payload.fields);
    return action;
  }
  async interceptLoadData(action) {
    var _a;
    const hasInvalidFilters = !filterValidate.validateFilters((_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.filterConfig);
    if (hasInvalidFilters) {
      const errorTitle = this.messagesBuilder.getMessage("snkGrid.requiredFiltersNotFilled.title", {});
      const errorMessage = this.messagesBuilder.getMessage("snkGrid.requiredFiltersNotFilled.message", {});
      await this._application.error(errorTitle, errorMessage);
      return;
    }
    return action;
  }
  finishLoading() {
    this._dataUnit.addInterceptor(this.dataUnitInterceptor);
    SnkMultiSelectionListDataSource.CrudUtils.assertDefaultSorting(this._gridConfig, this._dataUnit);
    this.addElementID();
    if (this.columnFilterDataSource != undefined) {
      this.columnFilterDataSource.setApplication(this._application);
      this.columnFilterDataSource.setDataUnit(this._dataUnit);
    }
  }
  setCustomRenders() {
    if (!this._grid) {
      return;
    }
    for (const [fieldName, customRenderProps] of this._customRenders) {
      this._grid.addGridCustomRender(fieldName, customRenderProps.customRender, customRenderProps.detailContext);
      this._customRenders.delete(fieldName);
    }
  }
  setCustomEditors() {
    if (!this._grid) {
      return;
    }
    for (const [fieldName, customEditorProps] of this._customEditors) {
      this._grid.addCustomEditor(fieldName, customEditorProps.customEditor, customEditorProps.detailContext);
      this._customEditors.delete(fieldName);
    }
  }
  componentWillLoad() {
    this._application = core.ApplicationContext.getContextValue('__SNK__APPLICATION__');
    //TODO: substituir pelo metodo nativo closest
    let parent = this._element.parentElement;
    while (parent) {
      if (parent.tagName.toUpperCase() === 'SNK-DATA-UNIT') {
        this._snkDataUnit = parent;
        this._dataUnit = this._snkDataUnit.dataUnit;
        if (!this._dataUnit) {
          this._snkDataUnit.addEventListener('dataUnitReady', (evt) => {
            this._dataUnit = evt.detail;
            this.finishLoading();
          });
        }
        else {
          this.finishLoading();
        }
        if (!this.messagesBuilder)
          this.messagesBuilder = this._snkDataUnit.messagesBuilder;
        this._snkDataUnit.addEventListener('dataStateChange', this.handleDataStateChange.bind(this));
        this._snkDataUnit.addEventListener('cancelEdition', () => {
          var _a;
          if ((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.recordsIsEmpty) {
            this._dataUnit.clearSelection();
          }
        });
        break;
      }
      parent = parent.parentElement;
    }
    this._rmPrecisionCustomValueFormatter = new SnkMultiSelectionListDataSource.RmPrecisionCustomValueFormatter();
    this.addGridLegacyConfigName();
    this.loadConfig();
    this._continuousInsertUtils = new SnkMultiSelectionListDataSource.ContinuousInsertUtils(this._application, this.resourceID, this.configName);
    if (this.enableGridInsert) {
      this._continuousInsertUtils.getConfig().then(value => this._enableContinuousInsert = value);
    }
  }
  componentDidRender() {
    var _a, _b;
    this._rmPrecisionCustomValueFormatter.setGrid(this._grid);
    this.loadGridCustomFormatters((_b = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.fields);
    this.setCustomRenders();
    this.setCustomEditors();
  }
  async handleDataStateChange(evt) {
    this._dataState = evt.detail;
    this._rmPrecisionCustomValueFormatter.setDataState(this._dataState);
  }
  getHeaderDisabledButtons() {
    var _a;
    const disabledButtons = [];
    if ((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.selectionInfo) {
      if (this._dataState.selectionInfo.length > 1) {
        disabledButtons.push(taskbarElements.TaskbarElement.CLONE, taskbarElements.TaskbarElement.ATTACH, taskbarElements.TaskbarElement.UPDATE);
      }
      if (this._dataState.selectionInfo.isAllRecords()) {
        disabledButtons.push(taskbarElements.TaskbarElement.REMOVE);
      }
    }
    return disabledButtons;
  }
  getInvisibleButtons() {
    var _a, _b;
    let invisibleButtons = [];
    if (!this._dataUnit || this._dataUnit.records.length === 0)
      invisibleButtons.push(taskbarElements.TaskbarElement.DATA_EXPORTER);
    if (((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.selectionInfo.mode) === DataUnit.SelectionMode.ALL_RECORDS)
      invisibleButtons.push(taskbarElements.TaskbarElement.ACTIONS_BUTTON);
    if (((_b = this._dataState) === null || _b === void 0 ? void 0 : _b.selectionInfo.length) === 1)
      invisibleButtons.push(taskbarElements.TaskbarElement.UPDATE_MULTIPLE);
    return invisibleButtons;
  }
  componentWillRender() {
    const invisibleButtons = this.getInvisibleButtons();
    this._headerTaskbarProcessor.process(this.getHeaderTaskbarId(), this.taskbarManager, this._dataState, this.getHeaderDisabledButtons(), invisibleButtons);
    this._topTaskbarProcessor.process(this.getTopTaskBarId(), this.taskbarManager, this._dataState, undefined, invisibleButtons);
    this.dataExporterProviderStore();
  }
  getHeaderTaskbarId() {
    var _a, _b;
    const hasSelectedRecord = this._dataState && !!((_a = this._dataState.selectionInfo) === null || _a === void 0 ? void 0 : _a.length);
    const taskbarIdPrefixLookup = {
      primary: this.isDetail ? 'snkGridHeaderTaskbar.detail' : 'snkGridHeaderTaskbar',
      secondary: this.isDetail ? 'snkGridHeaderTaskbar.detail' : 'snkGridHeaderTaskbar',
      singleTaskbar: this.isDetail ? 'snkGridHeaderTaskbar.singleTaskbar.detail' : 'snkGridHeaderTaskbar.singleTaskbar',
    };
    const taskbarIdPrefix = taskbarIdPrefixLookup[this.presentationMode];
    let headerTaskbarId = hasSelectedRecord ? `${taskbarIdPrefix}.selected` : `${taskbarIdPrefix}.unselected`;
    if (((_b = this._dataState) === null || _b === void 0 ? void 0 : _b.isDirty) && this.presentationMode === index$1.PresentationMode.SINGLE_TASKBAR) {
      headerTaskbarId = 'snkGridHeaderTaskbar.singleTaskbar.finish_edition';
    }
    return headerTaskbarId;
  }
  getTopTaskBarId() {
    var _a;
    const suffixLookup = {
      primary: '',
      secondary: '.secondary',
      singleTaskbar: '.singleTaskbar',
    };
    const sufix = suffixLookup[this.presentationMode];
    if ((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.isDirty) {
      return `snkGridTopTaskbar.finish_edition${sufix}`;
    }
    return `snkGridTopTaskbar.regular${sufix}`;
  }
  getPrimaryButton() {
    const primaryButtonLookup = {
      primary: 'INSERT',
      secondary: '',
      singleTaskbar: 'INSERT',
    };
    return primaryButtonLookup[this.presentationMode];
  }
  getColumnSearch(item) {
    if (this._columnSearch != undefined) {
      return this._columnSearch;
    }
    this._columnSearch = utils.buildFieldSearch(item, ({ argument }) => new Promise(accept => {
      this._grid.filterColumns(argument).then((columns) => {
        accept(columns
          .filter(column => !column.hidden)
          .map(column => ({ label: column.label, value: column.name })));
      });
    }), (option) => {
      if (option != undefined) {
        this._grid.locateColumn(option.value);
      }
    });
    return this._columnSearch;
  }
  getActionsList() {
    const hardList = [];
    if (this.enableGridInsert) {
      hardList.push(this._continuousInsertUtils.actionContinuousInsert(this._enableContinuousInsert, () => {
        this._enableContinuousInsert = !this._enableContinuousInsert;
        this._continuousInsertUtils.handleSaveConfig(this._enableContinuousInsert);
      }));
    }
    if (this.isGridInsertActive())
      return hardList;
    if (this.taskbarManager != undefined && this.taskbarManager.getMoreOptions != undefined) {
      const taskbarID = this.getTopTaskBarId();
      return hardList.concat(this.taskbarManager.getMoreOptions(taskbarID, this.configName, this._dataState, this.actionsList));
    }
    return hardList.concat(this.actionsList);
  }
  getActionsSettingsList() {
    const hardList = [{
        value: core.StringUtils.generateUUID(),
        label: this.messagesBuilder.getMessage('snkGrid.findColumn', {}),
        disableCloseOnSelect: true,
        eagerInitialize: true,
        itemBuilder: (_, item) => this.getColumnSearch(item),
      }];
    return hardList;
  }
  handleFilterConfigUpdated(filterConfig) {
    if (!filterConfig.length) {
      this._showSnkFilterBar = false;
      return;
    }
    if (filterConfig.length === 1 && filterConfig[0].id === 'PERSONALIZED_FILTER_GROUP') {
      this._showSnkFilterBar = filterConfig[0].groupedItems.length > 0;
      return;
    }
    this._showSnkFilterBar = true;
  }
  getGridHeaderButtons() {
    if (this.isGridInsertActive())
      return taskbarElements.TaskbarElement.MORE_OPTIONS;
    return this._headerTaskbarProcessor.buttons;
  }
  isGridInsertActive() {
    return this.enableGridInsert && this._dataUnit.hasNewRecord();
  }
  render() {
    if (!this._dataUnit) {
      return undefined;
    }
    return (index.h("div", { class: "snk-grid__container ez-flex ez-flex--column ez-flex-item--auto ez-padding--large ez-box--no-outline", tabindex: "0" }, index.h("div", { class: "snk-grid__header" }, this._showSnkFilterBar &&
      index.h(index.Fragment, null, index.h("snk-filter-bar", { ref: (ref) => this._snkFilterBar = ref, title: this.filterBarTitle, dataUnit: this._dataUnit, "data-element-id": "gridFilter", class: "snk-grid__filter-bar ez-align--top", configName: this.configName, messagesBuilder: this.messagesBuilder, resourceID: this.resourceID, onConfigUpdated: evt => this.handleFilterConfigUpdated(evt.detail), disablePersonalizedFilter: this.disablePersonalizedFilter, filterBarLegacyConfigName: this.filterBarLegacyConfigName, autoLoad: this.autoLoad, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, filterCustomConfig: this.filterCustomConfig, filterCustomConfigInterceptor: this.filterCustomConfigInterceptor }), index.h("hr", { class: "ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-grid__header-divider" })), index.h("snk-taskbar", { class: "ez-padding-left--medium ez-padding-top--extra-small", "data-element-id": "grid_top", key: "topTaskbar", configName: this.configName, dataUnit: this._dataUnit, messagesBuilder: this.messagesBuilder, buttons: this._topTaskbarProcessor.buttons, disabledButtons: this._topTaskbarProcessor.disabledButtons, customButtons: this._topTaskbarProcessor.customButtons, primaryButton: this.getPrimaryButton(), resourceID: this.resourceID, customContainerId: this.taskbarCustomContainerId, customSlotId: this.topTaskbarCustomSlotId, overflowStrategy: 'none', actionsSettingsList: this.getActionsSettingsList() }, index.h("slot", { name: this.topTaskbarCustomSlotId }))), index.h("ez-grid", { ref: ref => this._grid = ref, class: (this.presentationMode === index$1.PresentationMode.SECONDARY ? 'snk-grid-container__without-shadow ' : '') + 'snk-grid__table', "data-element-id": "embedded", dataUnit: this._dataUnit, key: 'grid-' + this._snkDataUnit.entityName, config: this._gridConfig, onConfigChange: (evt) => {
        this.gridConfigChangeHandler(evt);
      }, onEzColumnFilterChanged: async () => await this.dataExporterProviderStore(), onEzDoubleClick: (evt) => this.gridDoubleClick.emit(evt.detail), statusResolver: this.statusResolver, multipleSelection: this.multipleSelection, columnfilterDataSource: this.columnFilterDataSource, selectionToastConfig: this.selectionToastConfig, useEnterLikeTab: this.useEnterLikeTab, recordsValidator: this.recordsValidator, canEdit: this.canEdit, autoFocus: this.autoFocus, enableGridInsert: this.enableGridInsert, enableContinuousInsert: this._enableContinuousInsert, enableLockManagerTaskbarClick: this.enableLockManagerTaskbarClick, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, outlineMode: this.outlineMode, useSearchColumn: this.useSearchColumn, suppressHorizontalScroll: this.suppressHorizontalScroll, paginationCounterMode: this.paginationCounterMode, suppressCheckboxColumn: this.suppressCheckboxColumn, suppressFilterColumn: this.suppressFilterColumn, compact: this.compact }, index.h("snk-taskbar", { id: 'teste', dataUnit: this._dataUnit, configName: this.configName, messagesBuilder: this.messagesBuilder, "data-element-id": "grid_left", buttons: this.getGridHeaderButtons(), presentationMode: this.presentationMode, disabledButtons: this._headerTaskbarProcessor.disabledButtons, customButtons: this._headerTaskbarProcessor.customButtons, slot: "leftButtons", actionsList: this.getActionsList(), primaryButton: this.getPrimaryButton(), resourceID: this.resourceID, customContainerId: this.taskbarCustomContainerId, customSlotId: this.gridHeaderCustomSlotId, actionsSettingsList: this.getActionsSettingsList() }, index.h("slot", { name: this.gridHeaderCustomSlotId }))), index.h("div", { class: "ez-col ez-col--sd-12 snk-grid-container__footer" }, index.h("slot", { name: "SnkGridFooter" })), index.h("ez-popup", { size: "medium", heightMode: "auto", useHeader: false, opened: this._popUpGridConfig, onEzClosePopup: () => this.closeGridConfig() }, index.h("snk-grid-config", { ref: ref => this._snkGridConfig = ref, config: this._gridConfig, "data-element-id": this._element.getAttribute(core.ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME), selectedIndex: 0, configName: this.configName, onConfigChange: (evt) => this.modalConfigChangeHandler(evt), onConfigCancel: () => this.closeGridConfig(), resourceID: this.resourceID }))));
  }
  get _element() { return index.getElement(this); }
  static get watchers() { return {
    "gridLegacyConfigName": ["handleGridLegacyConfigName"]
  }; }
};
SnkGrid.style = snkGridCss;

exports.snk_grid = SnkGrid;
