import { r as registerInstance, e as createEvent, h, F as Fragment, g as getElement } from './index-e9c7ceaa.js';
import { KeyboardManager, Action, ElementIDUtils, ApplicationContext, StringUtils } from '@sankhyalabs/core';
import { SelectionMode } from '@sankhyalabs/core/dist/dataunit/DataUnit';
import { buildFieldSearch } from '@sankhyalabs/ezui/dist/collection/utils';
import './DataFetcher-955ee53e.js';
import './ISave-c8bf12c4.js';
import { C as CommonsExporter, S as SnkMultiSelectionListDataSource, a as CrudUtils, R as RmPrecisionCustomValueFormatter, b as ContinuousInsertUtils, c as ClientSideExporterProvider } from './SnkMultiSelectionListDataSource-100784a8.js';
import { P as PresentationMode, E as ExporterStrategy } from './index-b40568ff.js';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import './dataunit-fetcher-6cacb959.js';
import './filter-item-type.enum-d45e026f.js';
import './form-config-fetcher-baa89098.js';
import './constants-7b422de0.js';
import { C as ConfigStorage } from './ConfigStorage-4eee53da.js';
import { s as store } from './index-c961465b.js';
import { g as getSelectedRecordsIDsInfo } from './GetSelectedRecordsIDsInfo-9fa41508.js';
import { v as validateFilters } from './filter-validate-faf51fa9.js';
import { T as TaskbarElement } from './taskbar-elements-b3c5a3ce.js';
import { T as TaskbarProcessor } from './taskbar-processor-3436124c.js';
import './PrintUtils-3e4ff0f5.js';
import './IFetchDataExporterParams-d73bed3d.js';
import '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils/InMemoryFilterColumnDataSource';
import '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils';
import '@sankhyalabs/core/dist/utils/SortingUtils';
import './ResourceIDUtils-a114189a.js';

class ServerSideExporterProvider extends 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(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) {
    registerInstance(this, hostRef);
    this.actionClick = createEvent(this, "actionClick", 7);
    this.gridDoubleClick = createEvent(this, "gridDoubleClick", 7);
    this.componentReady = createEvent(this, "componentReady", 7);
    this._customEditors = new Map();
    this._customRenders = new Map();
    this._keyboardManager = new KeyboardManager();
    this._topTaskbarProcessor = new 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({
      '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 === Action.METADATA_LOADED) {
          return await this.interceptMetadataLoaded(action);
        }
        if (action.type === 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();
    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 = 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 = 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 = [
      TaskbarElement.UPDATE, TaskbarElement.CLONE, TaskbarElement.REMOVE,
      TaskbarElement.MORE_OPTIONS, TaskbarElement.DIVIDER, TaskbarElement.ATTACH, TaskbarElement.FORM_MODE,
      TaskbarElement.CONFIGURATOR, TaskbarElement.REFRESH, TaskbarElement.DATA_EXPORTER, TaskbarElement.ACTIONS_BUTTON,
    ];
    if (this.multipleEditionEnabled)
      btns.unshift(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 ? 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;
    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.loadGridConfig(this.configName, this.resourceID)
      .then((config) => {
      this.setGridConfig(this.normalizeGridConfig(config));
    })
      .catch((error) => {
      console.warn(error);
    });
  }
  addGridLegacyConfigName() {
    if (this.gridLegacyConfigName && this.configName) {
      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.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 === ExporterStrategy.CLIENT_SIDE)
      ? new ClientSideExporterProvider(this._dataUnit, this._grid)
      : new ServerSideExporterProvider(this._dataUnit, this._grid);
    store.set('exporterProviders', Object.assign(Object.assign({}, store.get('exporterProviders')), { [this.configName]: dataExporterProvider }));
  }
  addElementID() {
    const dataInfo = { dataUnit: this._dataUnit };
    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 = !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);
    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 = 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 RmPrecisionCustomValueFormatter();
    this.addGridLegacyConfigName();
    this.loadConfig();
    this._continuousInsertUtils = new 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(TaskbarElement.CLONE, TaskbarElement.ATTACH, TaskbarElement.UPDATE);
      }
      if (this._dataState.selectionInfo.isAllRecords()) {
        disabledButtons.push(TaskbarElement.REMOVE);
      }
    }
    return disabledButtons;
  }
  getInvisibleButtons() {
    var _a, _b;
    let invisibleButtons = [];
    if (!this._dataUnit || this._dataUnit.records.length === 0)
      invisibleButtons.push(TaskbarElement.DATA_EXPORTER);
    if (((_a = this._dataState) === null || _a === void 0 ? void 0 : _a.selectionInfo.mode) === SelectionMode.ALL_RECORDS)
      invisibleButtons.push(TaskbarElement.ACTIONS_BUTTON);
    if (((_b = this._dataState) === null || _b === void 0 ? void 0 : _b.selectionInfo.length) === 1)
      invisibleButtons.push(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 === 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 = 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: 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 TaskbarElement.MORE_OPTIONS;
    return this._headerTaskbarProcessor.buttons;
  }
  isGridInsertActive() {
    return this.enableGridInsert && this._dataUnit.hasNewRecord();
  }
  render() {
    if (!this._dataUnit) {
      return undefined;
    }
    return (h("div", { class: "snk-grid__container ez-flex ez-flex--column ez-flex-item--auto ez-padding--large ez-box--no-outline", tabindex: "0" }, h("div", { class: "snk-grid__header" }, this._showSnkFilterBar &&
      h(Fragment, null, 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 }), h("hr", { class: "ez-divider-vertical ez-divider--dark ez-margin-left--medium snk-grid__header-divider" })), 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() }, h("slot", { name: this.topTaskbarCustomSlotId }))), h("ez-grid", { ref: ref => this._grid = ref, class: (this.presentationMode === 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 }, 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() }, h("slot", { name: this.gridHeaderCustomSlotId }))), h("div", { class: "ez-col ez-col--sd-12 snk-grid-container__footer" }, h("slot", { name: "SnkGridFooter" })), h("ez-popup", { size: "medium", heightMode: "auto", useHeader: false, opened: this._popUpGridConfig, onEzClosePopup: () => this.closeGridConfig() }, h("snk-grid-config", { ref: ref => this._snkGridConfig = ref, config: this._gridConfig, "data-element-id": this._element.getAttribute(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 getElement(this); }
  static get watchers() { return {
    "gridLegacyConfigName": ["handleGridLegacyConfigName"]
  }; }
};
SnkGrid.style = snkGridCss;

export { SnkGrid as snk_grid };
