import { DataType, LockManager, LockManagerOperation, MaskFormatter, NumberUtils, SortMode, StringUtils, UserInterface, } from '@sankhyalabs/core';
import { Grid, } from "@ag-grid-community/core";
import { LicenseManager } from '@ag-grid-enterprise/core';
import DataSource from './DataSource';
import { EzGridCustomHeader } from './components/EzGridCustomHeader';
import { CellRendererStatus } from './components/cellRendererStatus';
import SelectionHeader from './components/selectionHeader';
import { DISTINCT_FILTER_NAME_PREFIX, EZ_GRID_LOADING_SOURCE, PRESENTATION_COL_ID_PROP_NAME, PRESENTATION_FROM_COL_PROP_NAME } from '../../../../utils/constants';
import GridEditionManager from './GridEditionManager';
import { ModuleRegistry } from '@ag-grid-community/core';
import { EnterpriseCoreModule } from '@ag-grid-enterprise/core';
import { RangeSelectionModule } from '@ag-grid-enterprise/range-selection';
import { ServerSideRowModelModule } from '@ag-grid-enterprise/server-side-row-model';
import { ClipboardModule } from '@ag-grid-enterprise/clipboard';
import { MenuModule } from '@ag-grid-enterprise/menu';
import DOMPurify from 'dompurify';
import { buildLocaleText } from './utils/buildLocaleText';
import { agGridLicense } from '../../../../utils/ag-grid-license';
export default class AgGridController {
  configFilterColumn(filterColumn) {
    this._filterColumn = filterColumn;
    this._filterColumn.addEventListener('applyFilterColumnOptions', this.handleFilteredColumnsChanged.bind(this));
  }
  handleFilteredColumnsChanged(event) {
    const applied = event.detail;
    this._filteredColumns.set(applied.field, applied.values);
    this._gridOptions.api.refreshHeader();
    this._dataUnit.loadData(undefined, undefined, undefined, EZ_GRID_LOADING_SOURCE);
  }
  clearFilter() {
    this._filteredColumns.clear();
    this._gridOptions.api.refreshHeader();
  }
  showFilterColumn(configs) {
    var _a;
    const presentationMetadata = this.resolveDescriptionColMetadata(configs.columnName);
    (_a = this._filterColumn) === null || _a === void 0 ? void 0 : _a.show(Object.assign(Object.assign({}, configs), { fieldDescriptor: presentationMetadata }));
  }
  constructor(_enterprise) {
    this.DEFAULT_ROW_HEIGHT = 30;
    this.DEFAULT_HEADER_ROW_HEIGHT = 32;
    this.CHECK_BOX_COL_ID = 'checkBoxColumn';
    this.STATUS_COL_ID = 'statusColumn';
    this.RECORD_ARCHIVE_COL_ID = '__RECORD_ARCHIVE__';
    this.BLOCK_LOAD_DEBOUNCE = 100;
    this.DEFAULT_FONT_SIZE = 14;
    this.DEFAULT_FONT_SIZE_HTML5 = 32;
    this.DEFAULT_ICON_SIZE = 12;
    this.DEFAULT_MAX_SIZE = 200;
    this._menuItems = [];
    this._idAttribName = '__record__id__';
    this._gridConfig = [];
    this._filteredColumns = new Map();
    this._filterColumnleftPosition = 0;
    this._customFormatters = new Map();
    this._gridShowDom = false;
    this.peddingExecutionsOnGridShow = [];
    this._lastColsConfig = undefined;
    ModuleRegistry.registerModules([
      EnterpriseCoreModule,
      RangeSelectionModule,
      ServerSideRowModelModule,
      ClipboardModule,
      MenuModule
    ]);
  }
  getGridConfig() {
    return this._gridConfig;
  }
  locateColumn(columnName, gridElement) {
    this._gridOptions.api.ensureColumnVisible(columnName);
    requestAnimationFrame(() => {
      this.highlightColumnHeader(columnName, gridElement);
    });
  }
  highlightColumnHeader(columnName, gridElement) {
    const headerElement = gridElement.querySelector(`.ag-header-cell[col-id="${columnName}"]`);
    if (!headerElement)
      return;
    headerElement.classList.add("ez-grid__column-highlight-header");
    headerElement.setAttribute("tabindex", "0");
    const removeHighlight = (event) => {
      if (!headerElement.contains(event.target)) {
        headerElement.classList.remove("ez-grid__column-highlight-header");
        document.removeEventListener("click", removeHighlight);
      }
    };
    document.addEventListener("click", removeHighlight);
  }
  getSort(_dataUnitName, defaultSorting) {
    const sortedColumns = [];
    this._gridOptions.columnApi
      .getColumnState()
      .sort((colA, colB) => colA.sortIndex - colB.sortIndex)
      .forEach(({ colId, sort }) => {
      if (sort) {
        const field = this._dataUnit.getField(colId);
        const mode = sort === 'asc' ? SortMode.ASC : SortMode.DESC;
        const sortField = field ? { field: field.name, dataType: field.dataType, mode } : { field: colId, dataType: DataType.TEXT, mode };
        sortedColumns.push(sortField);
      }
    });
    return sortedColumns.length === 0 && this._gridConfig === undefined ? defaultSorting : sortedColumns;
  }
  getFilter() {
    if (!this._filteredColumns || this._filteredColumns.size === 0) {
      return;
    }
    return Array.from(this._filteredColumns.entries())
      .map(([col, items]) => {
      var _a;
      const checkedOptions = items.filter(option => option.check);
      if (checkedOptions.length > 0) {
        let column = col;
        const presentationFrom = this.getCodeColFromDescriptionCol(col);
        if (!StringUtils.isEmpty(presentationFrom)) {
          column = presentationFrom;
        }
        const fieldDescriptor = this._dataUnit.getField(column);
        const dataType = (_a = fieldDescriptor === null || fieldDescriptor === void 0 ? void 0 : fieldDescriptor.dataType) !== null && _a !== void 0 ? _a : DataType.TEXT;
        let placeholders = '';
        const params = [];
        let isNullIncluded;
        checkedOptions.forEach(option => {
          const paramName = `PARAM_${column}_${params.length + 1}`;
          params.push({
            dataType: dataType === DataType.OBJECT ? DataType.TEXT : dataType,
            name: paramName,
            value: option.value,
          });
          if (option.value == undefined) {
            isNullIncluded = true;
          }
          else {
            if (placeholders.length > 0) {
              placeholders = placeholders + ',';
            }
            placeholders = `${placeholders}:${paramName}`;
          }
        });
        return {
          name: `${DISTINCT_FILTER_NAME_PREFIX}${column}`,
          expression: this.getExpression(dataType, column, placeholders, isNullIncluded),
          params,
        };
      }
      return undefined;
    })
      .filter(item => item != undefined);
  }
  getExpression(dataType, columnName, placeholders, isNullIncluded) {
    const columnExpression = dataType === DataType.DATE ? `onlydate(this.${columnName})` : `this.${columnName}`;
    if (placeholders.length > 0 && isNullIncluded) {
      return `(${columnExpression} in (${placeholders}) OR ${columnName} IS NULL)`;
    }
    if (isNullIncluded) {
      return `${columnName} IS NULL`;
    }
    return `${columnExpression} in (${placeholders})`;
  }
  initDatagrid(container, options) {
    var _a;
    this._options = options;
    this._container = container;
    const lockerIdTaskbarClick = (options === null || options === void 0 ? void 0 : options.enableLockManagerTaskbarClick) ? LockManager === null || LockManager === void 0 ? void 0 : LockManager.addLockManagerCtxId(this._container) : null;
    let resolveLoading = undefined;
    if (options === null || options === void 0 ? void 0 : options.enableLockManagerLoadingComp) {
      const lockerIdAppLoading = LockManager === null || LockManager === void 0 ? void 0 : LockManager.addLockManagerCtxId(this._container);
      resolveLoading = LockManager === null || LockManager === void 0 ? void 0 : LockManager.lock(lockerIdAppLoading, LockManagerOperation.APP_LOADING);
    }
    if (this._grid === undefined) {
      LicenseManager.setLicenseKey(agGridLicense);
      this._i18n = options.i18n;
      this._columnStateChangeCallback = options.onColumnStateChange;
      this._selectionChangeCallback = options.onSelectionChange;
      this._doubleClickCallBack = options.onDoubleClick;
      this._multipleSelection = options.allowMultipleSelection;
      this._dataUnit = options.dataUnit;
      this._editionManager = new GridEditionManager(this._dataUnit, options.useEnterLikeTab, options.recordsValidator, options.editionIsDisabled, options.customEditors || this._customEditors, options.customRenders || this._customRenders, options.enableContinuousInsert, options.enableGridInsert, lockerIdTaskbarClick);
      this._statusResolver = options.statusResolver;
      if (this._dataUnit) {
        this._dataUnit.sortingProvider = this;
        this._dataUnit.addFilterProvider(this);
      }
      this._gridOptions = {
        suppressHorizontalScroll: options.suppressHorizontalScroll,
        localeText: buildLocaleText(this._options.i18n),
        enableRangeSelection: this._multipleSelection,
        rowSelection: this._multipleSelection ? 'multiple' : 'single',
        sortingOrder: ['desc', 'asc', null],
        blockLoadDebounceMillis: this.BLOCK_LOAD_DEBOUNCE,
        navigateToNextCell: this.navigateToNextCell.bind(this),
        getRowNodeId: this._dataUnit ? params => (typeof params === 'string' ? params : params[this._idAttribName]) : undefined,
        getMainMenuItems: (params) => this.buildMenuItemOptions(params),
        postProcessPopup: (params) => this.setFilterColumnLeftPosition(params),
        getRowHeight: this.getRowHeight.bind(this),
        defaultColDef: {
          headerClass: 'ez-grid__cell-header',
          cellClass: 'ez-grid__cell-body',
          cellClassRules: {
            'invalidValue': (params) => this._editionManager.hasInvalidField(params.colDef.field, params.data["__record__id__"]),
          },
          cellStyle: {
            height: '100%'
          }
        },
        rowClassRules: {
          'row-striped': ({ node }) => (options.enableRowTableStriped && node.rowIndex % 2 === 0),
        },
        suppressFieldDotNotation: true,
        components: Object.assign({ ezGridHeaderComponent: SelectionHeader, ezGridCustomHeader: EzGridCustomHeader }, this._editionManager.getComponents()),
        context: {
          editionManager: this._editionManager,
          dataUnit: this._dataUnit,
          headerCheckStatusGetter: () => this.getSelectionHeaderStatus(),
          headerCheckStatusSetter: (selectAll) => this.updateSelectionForAll(selectAll),
        },
        processCellForClipboard: this.processFormatterCellCallback,
        defaultExcelExportParams: {
          processCellCallback: this.processFormatterCellCallback
        },
        defaultCsvExportParams: {
          processCellCallback: this.processFormatterCellCallback
        }
      };
      this.defineRowModelType(this._gridOptions, options, resolveLoading);
      this.setOptionsEvents(this._gridOptions);
      this.setOptionsSupress(this._gridOptions);
      this._gridOptions = this._editionManager.configureGrid(this._gridOptions);
      this._grid = new Grid(container, this._gridOptions);
      const selection = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.getSelectionInfo();
      if (selection === null || selection === void 0 ? void 0 : selection.isAllRecords()) {
        this.selectAll(true);
      }
      else {
        this.selectRows((selection === null || selection === void 0 ? void 0 : selection.recordIds) || [], true);
      }
      this._gridOptions.api.setHeaderHeight(this.getHeaderRowHeight());
      this._customFormatters = options.customFormatters;
      const observerCallback = (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            this._gridShowDom = true;
            this.peddingExecutionsOnGridShow.forEach(func => func());
            this.peddingExecutionsOnGridShow = [];
          }
          else {
            this._gridShowDom = false;
          }
        });
      };
      this.observer = new IntersectionObserver(observerCallback, {
        root: null,
        threshold: 0.1
      });
      this.observer.observe(container);
    }
  }
  processFormatterCellCallback(params) {
    const column = params.column.getColDef();
    if (typeof column.valueFormatter === 'function') {
      const valueParams = {
        value: params.value,
        data: params.node.data,
        node: params.node,
        colDef: column,
        column: params.column,
        api: params.api,
        columnApi: params.columnApi,
        context: params.context,
      };
      return column.valueFormatter(valueParams);
    }
    return params.value;
  }
  setFilterColumnLeftPosition({ type, ePopup }) {
    if (type === 'columnMenu') {
      this._filterColumnleftPosition = ePopup.getBoundingClientRect().left;
      return;
    }
  }
  buildMenuItemOptions(params) {
    const col = params.column;
    const items = [];
    if (col.getColDef().sortable) {
      items.push(this.buildMenuItemOptionSort(params, 'asc'));
      items.push(this.buildMenuItemOptionSort(params, 'desc'));
      if (!this._options.suppressFilterColumn) {
        items.push(this.buildMenuItemFilterColumn(params));
      }
    }
    this._menuItems.forEach(m => items.push({
      icon: m.icon,
      name: m.label,
      action: () => m.action(params),
    }));
    items.push(this.buildMenuItemOptionPin(params));
    return items;
  }
  buildMenuItemOptionSort(params, sortOrder) {
    return {
      icon: sortOrder === 'asc' ? `<i class='ez-icon-ordem-ascendente'></i>` : `<i class='ez-icon-ordem-descendente'></i>`,
      name: sortOrder === 'asc' ? this._i18n("ez-grid.sortAscending") : this._i18n("ez-grid.sortDescending"),
      action: () => this.sortDataByColumn(params, sortOrder),
    };
  }
  buildMenuItemFilterColumn(params) {
    const columnName = params.column.getId();
    const columnLabel = params.column.getColDef().headerName;
    return {
      icon: `<i class='ez-icon-filter'></i>`,
      name: this._i18n("ez-grid.filter"),
      action: () => this.showFilterColumn({ columnName, columnLabel, leftPosition: this._filterColumnleftPosition, filteredOptions: this._filteredColumns.get(columnName) }),
    };
  }
  resolveDescriptionColMetadata(columnName) {
    var _a;
    const colDef = (_a = this._gridOptions.columnApi.getColumn(columnName)) === null || _a === void 0 ? void 0 : _a.getColDef();
    const presentationFrom = this.getCodeColFromDescriptionCol(columnName);
    if (!StringUtils.isEmpty(presentationFrom)) {
      return {
        label: colDef.headerName,
        name: columnName,
        userInterface: UserInterface.SHORTTEXT,
        dataType: DataType.TEXT,
        properties: {
          [PRESENTATION_FROM_COL_PROP_NAME]: presentationFrom
        }
      };
    }
    return undefined;
  }
  buildMenuItemOptionPin(params) {
    const { column, columnApi } = params;
    const isPinned = params.column.isPinned();
    return {
      icon: `<i class='ez-icon-${isPinned ? 'un-pin' : 'push-pin'}'></i>`,
      name: isPinned ? this._i18n("ez-grid.unpinColumn") : this._i18n("ez-grid.pinColumn"),
      action: () => {
        columnApi.applyColumnState({
          state: [{ colId: column.getColId(), pinned: column.isPinned() ? null : 'left' }],
        });
      },
    };
  }
  sortDataByColumn(params, order) {
    const col = params.column;
    const colApi = params.columnApi;
    if (col.getSort() === order) {
      colApi.applyColumnState({
        defaultState: { sort: null },
      });
    }
    else {
      colApi.applyColumnState({
        state: [{ colId: col.getColId(), sort: order }],
        defaultState: { sort: null },
      });
    }
  }
  getRowHeight() {
    return this.DEFAULT_ROW_HEIGHT;
  }
  getHeaderRowHeight() {
    return this.DEFAULT_HEADER_ROW_HEIGHT;
  }
  navigateToNextCell(params) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    switch (params.key) {
      case 'ArrowUp':
        if (((_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.hasPrevious()) === false) {
          return null;
        }
        this._gridOptions.api.deselectAll();
        if (((_b = params.nextCellPosition) === null || _b === void 0 ? void 0 : _b.rowIndex) < 0) {
          (_c = this._dataUnit) === null || _c === void 0 ? void 0 : _c.previousRecord();
          return null;
        }
        else {
          (_d = this._dataUnit) === null || _d === void 0 ? void 0 : _d.setSelectionByIndex([params.nextCellPosition.rowIndex]);
          return params.nextCellPosition;
        }
      case 'ArrowDown':
        if (((_e = this._dataUnit) === null || _e === void 0 ? void 0 : _e.hasNext()) === false) {
          return null;
        }
        this._gridOptions.api.deselectAll();
        if ((_f = params.nextCellPosition) === null || _f === void 0 ? void 0 : _f.rowIndex) {
          (_g = this._dataUnit) === null || _g === void 0 ? void 0 : _g.setSelectionByIndex([params.nextCellPosition.rowIndex]);
        }
        else {
          (_h = this._dataUnit) === null || _h === void 0 ? void 0 : _h.nextRecord();
        }
        return params.nextCellPosition;
      case 'ArrowLeft':
      case 'ArrowRight':
        if (((_j = params.nextCellPosition) === null || _j === void 0 ? void 0 : _j.column.colDef.headerName) !== '') {
          return params.nextCellPosition;
        }
        else {
          return null;
        }
    }
    return null;
  }
  defineRowModelType(opt, sourceOptions, resolveLoading) {
    if (this._dataUnit != undefined) {
      opt.rowModelType = 'serverSide';
      opt.serverSideDatasource = this._dataSource = new DataSource(this._dataUnit, this, sourceOptions, resolveLoading);
      opt.serverSideSortOnServer = true;
      opt.columnDefs = this._colDefs;
    }
  }
  setOptionsEvents(opt) {
    opt.onSortChanged = e => this.onCallStateChange('sort', e);
    opt.onColumnResized = e => this.onCallStateChange('columnResize', e);
    opt.onColumnPinned = e => this.onCallStateChange('columnPinned', e);
    opt.onColumnMoved = e => this.onCallStateChange('columnMoved', e);
    opt.onColumnVisible = e => this.onCallStateChange('visibleChange', e);
    opt.onSelectionChanged = e => this.onSelectionChange(e);
    opt.onRowDoubleClicked = evt => this.onRowDoubleClick(evt);
    opt.onDragStopped = evt => this.onCallStateChange('columnMovedEnd', evt);
    opt.onCellClicked = evt => this.onCellClicked(evt);
  }
  setOptionsSupress(opt) {
    opt.suppressDragLeaveHidesColumns = true;
    opt.suppressMenuHide = true;
  }
  getSelectionHeaderStatus() {
    const records = this._dataUnit.records;
    if (records && records.length === 0) {
      return false;
    }
    const selectionInfo = this._dataUnit.getSelectionInfo();
    if (selectionInfo.isAllRecords()) {
      return true;
    }
    const selection = selectionInfo.recordIds;
    if (selection == undefined || selection.length === 0) {
      return false;
    }
    let status = undefined;
    for (let i = 0; i < records.length; i++) {
      const current = selection.includes(records[i].__record__id__);
      if (status != undefined && current !== status) {
        return undefined;
      }
      status = current;
    }
    return status;
  }
  updateSelectionForAll(selectAll) {
    selectAll ? this._dataUnit.selectAllRecords() : this._dataUnit.unSelectAllRecords();
  }
  setData(data) {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
    this._gridOptions.api.setRowData(data);
  }
  addRows() {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
  }
  updateRows(rows) {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
    rows === null || rows === void 0 ? void 0 : rows.forEach(row => this.updateRowData(row));
  }
  updateRowData(row) {
    const node = this._gridOptions.api.getRowNode(row[this._idAttribName]);
    node.setData(Object.assign({}, row));
    this._editionManager.updateCurrentEditorGuiValue(row);
    this._editionManager.recordValidate();
  }
  selectAll(quietly = false) {
    try {
      this._gridOptions.context.selectionChangeQuietly = quietly;
      this._gridOptions.api.forEachNode(node => {
        if (!node.isSelected()) {
          node.setSelected(true);
        }
      });
    }
    finally {
      const newContext = Object.assign({}, this._gridOptions.context);
      delete newContext.selectionChangeQuietly;
      this._gridOptions.context = newContext;
    }
  }
  selectRows(rowIds, quietly = false) {
    var _a;
    try {
      this._gridOptions.context.selectionChangeQuietly = quietly;
      if (this._grid === undefined) {
        throw new Error('Erro interno: Grid ainda não inicializado.');
      }
      let lastSelected;
      this._gridOptions.api.forEachNode(node => {
        if (rowIds && rowIds.includes(node.id)) {
          if (!node.isSelected()) {
            node.setSelected(true);
            lastSelected = node;
          }
        }
        else {
          if (node.isSelected()) {
            node.setSelected(false);
          }
        }
      });
      const selectionHeader = this._gridOptions.context.selectionHeader;
      if (selectionHeader) {
        selectionHeader.updateCheckbox();
      }
      if (lastSelected) {
        (_a = this._gridOptions.api) === null || _a === void 0 ? void 0 : _a.ensureNodeVisible(lastSelected);
      }
    }
    finally {
      const newContext = Object.assign({}, this._gridOptions.context);
      delete newContext.selectionChangeQuietly;
      this._gridOptions.context = newContext;
    }
  }
  removeRows() {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
    this._gridOptions.api.refreshServerSide({ purge: true });
  }
  changeValues(changes, rowIds) {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
    if (changes) {
      let rowNodes;
      if (rowIds) {
        rowNodes = [];
        rowIds.forEach(id => {
          const rowNode = this._gridOptions.api.getRowNode(id);
          if (rowNode) {
            rowNodes.push(rowNode);
          }
        });
      }
      else {
        rowNodes = this._gridOptions.api.getSelectedNodes();
      }
      rowNodes.forEach(r => {
        const data = r.data;
        Object.entries(changes).forEach(([field, value]) => {
          data[field] = value;
        });
        r.setData(data);
      });
      this._gridOptions.api.refreshCells({ force: true });
      const invalidCell = this._editionManager.getNextInvalidCell();
      if (invalidCell) {
        const rowNode = this._gridOptions.api.getRowNode(invalidCell.recordId);
        if (rowNode && invalidCell.field) {
          this.startEdition(rowNode.rowIndex, this._gridOptions.columnApi.getColumn(invalidCell.field.name));
        }
      }
    }
  }
  savingCanceled(fields, recordId) {
    if (!this._gridShowDom)
      return;
    const displayedColumns = this._gridOptions.columnApi.getAllDisplayedColumns();
    const rowIndex = this._gridOptions.api.getRowNode(recordId).rowIndex;
    const columnFocus = displayedColumns.find(column => this.isColumnEditable(rowIndex, column) && fields.find(field => field.name === column.getColId()));
    this.focusByCollAndRow(columnFocus, rowIndex);
    this.startEdition(rowIndex, columnFocus);
  }
  refresh(scrollToSelectedRow = false) {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
    this._gridOptions.api.clearRangeSelection();
    this._gridOptions.api.refreshServerSide({ purge: true });
    this._options.onRefresh();
    if (scrollToSelectedRow)
      this.scrollToSelectedRow();
  }
  scrollToSelectedRow() {
    const rowNode = this._gridOptions.api.getSelectedNodes();
    if (!rowNode || rowNode.length === 0)
      return;
    if (this._gridShowDom) {
      this._gridOptions.api.ensureNodeVisible(rowNode[0]);
    }
    else {
      this.peddingExecutionsOnGridShow.push(() => this._gridOptions.api.ensureNodeVisible(rowNode[0]));
    }
  }
  focusOnGridContainer() {
    this._container.setAttribute('tabindex', '-1');
    this._container.focus();
  }
  setFocus() {
    var _a, _b;
    if (!((_b = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.records) === null || _b === void 0 ? void 0 : _b.length)) {
      this.focusOnGridContainer();
      return;
    }
    if (!this._dataUnit.getSelectedRecord()) {
      this.setFocusFirstRow();
      return;
    }
    this.syncSelectWithDataUnit();
  }
  setAutoFocus(autoFocus) {
    var _a;
    (_a = this._dataSource) === null || _a === void 0 ? void 0 : _a.setAutoFocus(autoFocus);
  }
  setEnableGridInsert(enable) {
    var _a;
    (_a = this._dataSource) === null || _a === void 0 ? void 0 : _a.setEnableGridInsert(enable);
  }
  setEnableContinuousInsert(enable) {
    var _a;
    (_a = this._editionManager) === null || _a === void 0 ? void 0 : _a.setEnableContinuousInsert(enable);
  }
  setFocusFirstRow() {
    const firstRow = this._gridOptions.api.getDisplayedRowAtIndex(0);
    if (firstRow) {
      this.setFocusOnRow(firstRow.rowIndex);
    }
    else {
      this.focusOnGridContainer();
    }
  }
  setFocusLastRow() {
    const lastRow = this._gridOptions.api.getDisplayedRowAtIndex(this._gridOptions.api.getLastDisplayedRow());
    if (lastRow) {
      this.setFocusOnRow(lastRow.rowIndex);
    }
  }
  startEditionOnRowByIndex(rowIndex) {
    this._dataUnit.setSelectionByIndex([rowIndex]);
    const firstCol = this.getFirstEditableColl(rowIndex);
    if (!firstCol)
      return;
    this.focusByCollAndRow(firstCol, rowIndex);
    this.startEdition(rowIndex, firstCol);
  }
  startEditionOnLastRow() {
    var _a;
    if (this._gridShowDom) {
      const newRowIndex = ((_a = this._dataUnit.records) === null || _a === void 0 ? void 0 : _a.length) - 1;
      this.startEditionOnRowByIndex(newRowIndex);
    }
  }
  syncSelectWithDataUnit() {
    const rowNode = this._gridOptions.api.getRowNode(this._dataUnit.getSelectedRecord().__record__id__);
    if (!rowNode || (rowNode === null || rowNode === void 0 ? void 0 : rowNode.rowIndex) < 0)
      return;
    const rowRange = this._gridOptions.api.getCellRanges().find(row => row.startRow.rowIndex === rowNode.rowIndex);
    if ((rowRange === null || rowRange === void 0 ? void 0 : rowRange.columns.length) > 0) {
      if (this._dataUnit.hasNewRecord()) {
        this.startEdition(rowNode.rowIndex, rowRange.columns[0]);
        return;
      }
      this.focusByCollAndRow(rowRange.columns[0], rowNode.rowIndex);
      this._gridOptions.api.addCellRange({ rowStartIndex: rowNode.rowIndex, rowEndIndex: rowNode.rowIndex, columns: rowRange.columns });
      return;
    }
    this._gridOptions.api.clearRangeSelection();
    this.setFocusOnRow(rowNode.rowIndex);
  }
  startEdition(rowIndex, firstCol) {
    if (!this._gridShowDom)
      return;
    this._gridOptions.api.clearRangeSelection();
    this._gridOptions.api.addCellRange({ rowStartIndex: rowIndex, rowEndIndex: rowIndex, columns: [firstCol] });
    this._gridOptions.api.setFocusedCell(rowIndex, firstCol);
    this._gridOptions.api.startEditingCell({ rowIndex, colKey: firstCol });
    const cellEditor = this._gridOptions.api.getCellEditorInstances()[0];
    if (cellEditor) {
      cellEditor.focusIn();
    }
  }
  getFirstEditableColl(rowIndex) {
    try {
      const displayedColumns = this._gridOptions.columnApi.getAllDisplayedColumns();
      return displayedColumns.find(column => this.isColumnEditable(rowIndex, column));
    }
    catch (e) {
      console.warn(e);
    }
  }
  isColumnEditable(rowIndex, column) {
    if (column.getColDef().headerName === ''
      || column.getColDef().headerName === this.CHECK_BOX_COL_ID
      || rowIndex === -1)
      return false;
    const rowId = this._dataUnit.records[rowIndex][this._idAttribName];
    const rowNode = this._gridOptions.api.getRowNode(rowId);
    return column.isCellEditable(rowNode);
  }
  setFocusOnRow(rowIndex) {
    let displayedColumns = this._gridOptions.columnApi.getAllDisplayedColumns();
    let firstColl = displayedColumns.find(column => column.getColDef().headerName !== '');
    this.focusByCollAndRow(firstColl, rowIndex);
    this._gridOptions.api.addCellRange({ rowStartIndex: rowIndex, rowEndIndex: rowIndex, columns: [firstColl] });
  }
  focusByCollAndRow(firstCell, rowIndex) {
    this._gridOptions.api.ensureColumnVisible(firstCell);
    this._gridOptions.api.ensureIndexVisible(rowIndex);
    this._gridOptions.api.setFocusedCell(rowIndex, firstCell);
  }
  setColumnsDef(cols) {
    const checkBoxColumn = Object.assign({ colId: this.CHECK_BOX_COL_ID, headerName: this.CHECK_BOX_COL_ID, checkboxSelection: true, width: 29, suppressMovable: true, suppressAutoSize: true, suppressMenu: true, lockPosition: true, pinned: true }, (this._multipleSelection ?
      { headerComponent: 'ezGridHeaderComponent', headerClass: 'ag-column-select-header' }
      : { headerComponentParams: { displayName: '' } }));
    const newColDefs = this._options.suppressCheckBoxCol ? [] : [checkBoxColumn];
    if (this._statusResolver != undefined) {
      newColDefs.push({
        colId: this.STATUS_COL_ID,
        headerName: '',
        checkboxSelection: false,
        headerCheckboxSelection: false,
        width: 29,
        suppressMovable: true,
        suppressAutoSize: true,
        suppressMenu: true,
        lockPosition: true,
        pinned: true,
        cellRenderer: CellRendererStatus,
        cellRendererParams: {
          statusResolver: this._statusResolver,
        },
        cellStyle: {
          'text-align': 'center',
        },
        suppressNavigable: true,
      });
    }
    cols.forEach(c => {
      newColDefs.push(this.buildColDef(c));
    });
    this._colDefs = newColDefs;
    if (this._gridOptions && this._gridOptions.api) {
      this.setColsDefsWithStateIfNeeded(this._colDefs);
    }
  }
  setColsDefsWithStateIfNeeded(colDefs) {
    if (!this._lastColsConfig) {
      this._gridOptions.api.setColumnDefs(this._colDefs);
    }
    /*
      Caso a definição de colunas esteja sendo atualizada,
      e existe uma config aplicada, temos que considerar essa
      config ao adicionar nova definição de colunas.
      PS: Poderia apenas chamar o setColumnsState, porém,
      isso impactaria em performance, e o usuário ia perceber
      a mudança das colunas visualmente na grade, o que traria
      uma experiencia ruim.
    */
    const colDefsWithConfigs = this.getColsDefWithConfigApplied(colDefs, this._lastColsConfig);
    this._gridOptions.api.setColumnDefs(colDefsWithConfigs);
  }
  getColsDefWithConfigApplied(colDefs, colsConfig = []) {
    //Cria map de colunas existentes na config e seu índice
    const orderMap = colsConfig.reduce((map, col, index) => {
      map[col.name] = index;
      return map;
    }, {});
    //Remove colunas que não existem na config
    const filteredColsDefs = colDefs.filter((col) => !orderMap.hasOwnProperty(col.colId));
    //Ordena colunas baseada na config aplicada
    const sortedColumnDefs = filteredColsDefs.sort((a, b) => {
      var _a, _b;
      return ((_a = orderMap[a.field]) !== null && _a !== void 0 ? _a : Number.MAX_VALUE) - ((_b = orderMap[b.field]) !== null && _b !== void 0 ? _b : Number.MAX_VALUE);
    });
    return sortedColumnDefs;
  }
  clearRangeSelection() {
    this._gridOptions.api.clearRangeSelection();
  }
  hideSelectionColumn() {
    var _a, _b;
    (_b = (_a = this._gridOptions) === null || _a === void 0 ? void 0 : _a.columnApi) === null || _b === void 0 ? void 0 : _b.setColumnVisible(this.CHECK_BOX_COL_ID, false);
  }
  showSelectionColumn() {
    var _a, _b;
    (_b = (_a = this._gridOptions) === null || _a === void 0 ? void 0 : _a.columnApi) === null || _b === void 0 ? void 0 : _b.setColumnVisible(this.CHECK_BOX_COL_ID, true);
  }
  getColumnsDef() {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
    const colDef = this._gridOptions.columnApi.getColumns();
    return colDef
      .filter(c => ![this.CHECK_BOX_COL_ID, this.STATUS_COL_ID].includes(c.getColId()))
      .map(c => {
      const def = c.getColDef();
      const colDef = { name: def.field, label: def.headerName };
      this.conditionalSet(colDef, 'sortable', def.sortable);
      this.conditionalSet(colDef, 'resizable', def.resizable);
      this.conditionalSet(colDef, 'sort', def.sort);
      this.conditionalSet(colDef, 'sortIndex', def.sortIndex);
      this.conditionalSet(colDef, 'width', def.width);
      this.conditionalSet(colDef, 'pinned', def.pinned !== null);
      this.conditionalSet(colDef, 'hidden', def.hide);
      return colDef;
    });
  }
  setColumnsState(state) {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
    this._lastColsConfig = state;
    const colDef = this._gridOptions.columnApi.getColumns();
    let columns = this.getColumnsDef();
    let visibleColumns = [];
    //Existem colunas implícitas que não tem estado, essas colunas são sempre as primeiras.
    //Como vamos reordenar, precisamos considerar o deslocamento provocado por elas.
    const columnsOffset = colDef.length - columns.length;
    this._gridConfig = state;
    let sort = [];
    let currentIndex = 0;
    state.forEach((cfgColumn) => {
      var _a, _b;
      const colWidth = this.getColumnWidth(cfgColumn);
      this._gridOptions.columnApi.moveColumn(cfgColumn.name, currentIndex + columnsOffset);
      this._gridOptions.columnApi.setColumnWidth(cfgColumn.name, colWidth);
      visibleColumns.push(cfgColumn.name);
      if (cfgColumn.ascending !== undefined) {
        sort.push({ colId: cfgColumn.name, sort: cfgColumn.ascending !== true ? 'desc' : 'asc', sortIndex: cfgColumn.orderIndex });
      }
      currentIndex++;
      const fieldMD = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.getField(cfgColumn.name);
      /*
        Migração para o SEARCHPLUS, caso de uso:
          - Agora existe uma coluna para o campo de descrição do relaciona
          - Essa col, não existe na config da grade que já foi salva pelo DS
          - Nesse caso, precisamos inserir a coluna de descrição automaticamente para que
            os usuários não percam a apresentação do campo de descrição.
          PS: Caso esteja herdando do HTML5, devemos manter a config como está la
      */
      if (this.needToAddDescriptionColumn(cfgColumn, fieldMD, state)) {
        const descriptionColID = (_b = fieldMD === null || fieldMD === void 0 ? void 0 : fieldMD.properties) === null || _b === void 0 ? void 0 : _b[PRESENTATION_COL_ID_PROP_NAME];
        if (!descriptionColID)
          return;
        const descriptionCol = this._gridOptions.columnApi.getColumn(descriptionColID);
        const descriptionColDef = descriptionCol === null || descriptionCol === void 0 ? void 0 : descriptionCol.getColDef();
        const descriptionHeaderName = descriptionColDef === null || descriptionColDef === void 0 ? void 0 : descriptionColDef.headerName;
        const descriptionColSize = this.getColumnWidthByLabel(descriptionHeaderName);
        this._gridOptions.columnApi.moveColumn(descriptionColID, currentIndex + columnsOffset);
        this._gridOptions.columnApi.setColumnWidth(descriptionColID, descriptionColSize);
        visibleColumns.push(descriptionColID);
        currentIndex++;
      }
    });
    let invisibleColumns = columns.filter(column => !visibleColumns.includes(column.name)).map(column => column.name);
    this._gridOptions.columnApi.setColumnsVisible(visibleColumns, true);
    this._gridOptions.columnApi.setColumnsVisible(invisibleColumns, false);
    this._gridOptions.columnApi.applyColumnState({
      state: sort,
      defaultState: { sort: null },
    });
  }
  needToAddDescriptionColumn(cfgColumn, fieldMD, stateConfig) {
    var _a, _b;
    if (!fieldMD) {
      return false;
    }
    const configVersion = ((_a = cfgColumn.configVersion) !== null && _a !== void 0 ? _a : 0);
    const isSearchPlus = (fieldMD === null || fieldMD === void 0 ? void 0 : fieldMD.userInterface) == UserInterface.SEARCHPLUS;
    const descriptionColID = (_b = fieldMD === null || fieldMD === void 0 ? void 0 : fieldMD.properties) === null || _b === void 0 ? void 0 : _b[PRESENTATION_COL_ID_PROP_NAME];
    return isSearchPlus && configVersion < 1 && stateConfig.find(col => col.name === descriptionColID) != undefined;
  }
  getColumnsState() {
    if (this._grid === undefined) {
      throw new Error('Erro interno: Grid ainda não inicializado.');
    }
    const colState = this._gridOptions.columnApi.getColumnState();
    return colState
      .map(s => {
      const column = this._gridOptions.columnApi.getColumn(s.colId);
      const def = column.getColDef();
      const width = column.getActualWidth();
      const label = def.headerName;
      const name = def.checkboxSelection ? '__SELECTION__' : s.colId;
      const colState = { label, name };
      this.conditionalSet(colState, 'sort', s.sort);
      this.conditionalSet(colState, 'sortIndex', s.sortIndex);
      this.conditionalSet(colState, 'width', width);
      this.conditionalSet(colState, 'pinned', s.pinned !== null);
      this.conditionalSet(colState, 'hidden', s.hide);
      const props = new Map();
      props.set('sortable', def.sortable);
      this.conditionalSet(colState, 'props', props);
      return colState;
    })
      .filter(c => c.name !== '__SELECTION__' && c.name !== this.STATUS_COL_ID);
  }
  getSelection() {
    return this._gridOptions.api.getSelectedRows();
  }
  addColumnMenuItem(item) {
    const itemsNames = this._menuItems.map(i => i.name);
    if (!itemsNames.includes(item.name)) {
      this._menuItems.push(item);
    }
  }
  quickFilter(term) {
    if (term) {
      const quickFilter = {
        term,
        fields: this._gridOptions.columnApi
          .getColumns()
          .filter(col => col.isVisible() && ![this.CHECK_BOX_COL_ID, this.STATUS_COL_ID, this.RECORD_ARCHIVE_COL_ID].includes(col.getColId()))
          .map(col => col.getColId()),
      };
      this._dataSource.quickFilter = quickFilter;
    }
    else {
      this._dataSource.quickFilter = undefined;
    }
  }
  setSelectedIndex(index) {
    var _a;
    (_a = this._gridOptions.api.getDisplayedRowAtIndex(index)) === null || _a === void 0 ? void 0 : _a.setSelected(true);
  }
  hasFilterColumn(columnName) {
    var _a;
    const filterOptions = (_a = this._filteredColumns.get(columnName)) !== null && _a !== void 0 ? _a : [];
    return filterOptions.map(item => item.check).includes(true);
  }
  buildColDef(source) {
    var _a, _b, _c, _d, _e;
    let tooltip = undefined;
    const propSortable = StringUtils.getBooleanValue((_a = source.props) === null || _a === void 0 ? void 0 : _a.get('gridSortable'), true);
    if ((_b = source.props) === null || _b === void 0 ? void 0 : _b.get('gridHeaderTooltip')) {
      tooltip = (_c = source.props) === null || _c === void 0 ? void 0 : _c.get('gridHeaderTooltip');
    }
    else if (propSortable === false) {
      tooltip = this._i18n('ez-grid.columnCantBeOrder');
    }
    const presentationFrom = (_d = source === null || source === void 0 ? void 0 : source.props) === null || _d === void 0 ? void 0 : _d.get(PRESENTATION_FROM_COL_PROP_NAME);
    return this._editionManager.configureColumn({
      headerName: source.label,
      field: source.name,
      sortable: propSortable,
      resizable: true,
      headerComponent: 'ezGridCustomHeader',
      headerComponentParams: {
        presentationFrom,
        tooltip: tooltip,
        isSortable: propSortable,
        hasFilter: () => this.hasFilterColumn(source.name),
        showColumnFilter: (leftPosition) => this.showFilterColumn({ columnName: source.name, columnLabel: source.label, leftPosition, filteredOptions: this._filteredColumns.get(source.name), fromIcon: true }),
      },
      valueFormatter: params => {
        var _a, _b, _c;
        if (presentationFrom) {
          return (_c = (_b = (_a = params === null || params === void 0 ? void 0 : params.data) === null || _a === void 0 ? void 0 : _a[presentationFrom]) === null || _b === void 0 ? void 0 : _b.label) !== null && _c !== void 0 ? _c : "";
        }
        if (params.value === undefined || params.value === null) {
          return "";
        }
        if (params.value instanceof Promise) {
          return `${this._i18n("app.loading")}...`;
        }
        if (source.userInterface === UserInterface.HTML) {
          this.setHTMLRender(params, source);
          return "";
        }
        const customFormatter = this._customFormatters.get(source.name);
        if (customFormatter) {
          const formattedValue = customFormatter.format(params.value, source, params.data.__record__id__);
          if (formattedValue) {
            return formattedValue;
          }
        }
        if (this._dataUnit) {
          return this._dataUnit.getFormattedValue(source.name, params.value);
        }
        return this.getFormatterByColumn(params, source);
      },
      cellStyle: this.getStyleByColumn(source),
      editable: !((_e = source.props) === null || _e === void 0 ? void 0 : _e.has(PRESENTATION_FROM_COL_PROP_NAME))
    });
  }
  setHTMLRender(params, source) {
    const htmlSanitized = DOMPurify.sanitize(params.value);
    params.colDef.cellRenderer = (cellParams) => {
      if (cellParams.node.rowIndex === params.node.rowIndex) {
        const element = document.createElement('span');
        element.innerHTML = htmlSanitized;
        return element;
      }
      return cellParams.value;
    };
    params.colDef.cellStyle = (cellParams) => {
      const defaultStyle = this.getStyleByColumn(source);
      if (cellParams.node.rowIndex === params.node.rowIndex) {
        return Object.assign(defaultStyle, { padding: 0 });
      }
      return defaultStyle;
    };
  }
  setCustomFormatters(customFormatters) {
    this._customFormatters = customFormatters;
  }
  refreshSelectedRows() {
    const selectedNodes = this._gridOptions.api.getSelectedNodes();
    this._gridOptions.api.redrawRows({ rowNodes: selectedNodes });
  }
  getInitCellStyle() {
    return {
      'line-height': this.getRowHeight() - 1 + 'px',
    };
  }
  getStyleByColumn(source) {
    var _a;
    let cellStyle = this.getInitCellStyle();
    const primitiveUIType = (_a = source === null || source === void 0 ? void 0 : source.props) === null || _a === void 0 ? void 0 : _a.get("PRIMITIVETUIYPE");
    const uitype = source === null || source === void 0 ? void 0 : source.userInterface;
    if (uitype === UserInterface.SEARCH) {
      cellStyle['text-align'] = 'left';
      return cellStyle;
    }
    switch (primitiveUIType !== null && primitiveUIType !== void 0 ? primitiveUIType : uitype) {
      case UserInterface.DECIMALNUMBER:
      case UserInterface.INTEGERNUMBER:
        cellStyle['text-align'] = 'right';
        break;
      case UserInterface.DATE:
      case UserInterface.DATETIME:
      case UserInterface.TIME:
        cellStyle['text-align'] = 'center';
        break;
      default:
        cellStyle['text-align'] = 'left';
    }
    return cellStyle;
  }
  getFormatterByColumn(params, source) {
    var _a, _b, _c, _d;
    if ((source === null || source === void 0 ? void 0 : source.userInterface) === 'OPTIONSELECTOR' && source.options) {
      const prop = source === null || source === void 0 ? void 0 : source.options;
      let options;
      if (typeof prop === 'string') {
        const parsed = JSON.parse(prop);
        options = Object.keys(parsed).map(key => {
          return { value: key, label: parsed[key] };
        });
      }
      else {
        options = prop;
      }
      let optionSelected;
      options.forEach(option => {
        if (option.value == params.value) {
          optionSelected = option;
        }
      });
      return optionSelected === null || optionSelected === void 0 ? void 0 : optionSelected.label;
    }
    if ((source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.SWITCH) {
      if ((params === null || params === void 0 ? void 0 : params.value) === 'S' || (params === null || params === void 0 ? void 0 : params.value) === true || (params === null || params === void 0 ? void 0 : params.value) === 'true') {
        return this._i18n("app.yes");
      }
      else if ((params === null || params === void 0 ? void 0 : params.value) === 'N' || (params === null || params === void 0 ? void 0 : params.value) === false || (params === null || params === void 0 ? void 0 : params.value) === 'false') {
        return this._i18n("app.no");
      }
    }
    if ((source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.SEARCH) {
      if (((_a = params === null || params === void 0 ? void 0 : params.value) === null || _a === void 0 ? void 0 : _a.value) != undefined) {
        return params.value.value + ' - ' + params.value.label;
      }
      else {
        return params === null || params === void 0 ? void 0 : params.value;
      }
    }
    if ((source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.SEARCHPLUS) {
      return (_d = (_c = (_b = params === null || params === void 0 ? void 0 : params.value) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : params === null || params === void 0 ? void 0 : params.value) !== null && _d !== void 0 ? _d : "";
    }
    if ((source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.DECIMALNUMBER) {
      if (params.value != undefined) {
        const precision = Number(source.props.get('precision')) || 2;
        return NumberUtils.format(params.value.toString(), precision, precision);
      }
    }
    if ((source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.DATE || (source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.DATETIME) {
      if (params.value != undefined) {
        return params.value.toLocaleDateString();
      }
    }
    if ((source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.ELAPSEDTIME || (source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.TIME) {
      if (!!params.value) {
        const maskFormatter = new MaskFormatter("##:##");
        const formattedValue = String(params.value).padStart(4, '0');
        return maskFormatter.format(formattedValue);
      }
    }
    if ((source === null || source === void 0 ? void 0 : source.userInterface) === UserInterface.FILE) {
      if (!params.value || !Array.isArray(params.value))
        return '';
      if (params.value.length === 1)
        return params.value[0].name;
      return `${params.value.length} arquivos`;
    }
  }
  onCallStateChange(type, e) {
    const finished = !('finished' in e) || e['finished'];
    if (finished && this._columnStateChangeCallback) {
      let info = {};
      let isUserChange = this.isUIEvent(e['source'], e['type']);
      if (type === 'columnResize') {
        info['column'] = { colId: e['column'].colId, actualWidth: e['column'].actualWidth };
      }
      info['isUserChange'] = isUserChange;
      info['isElementResize'] = this.isElementResize(e);
      this._columnStateChangeCallback(type, this.getColumnsState(), info);
    }
  }
  onCellClicked(event) {
    this._editionManager.verifyClickToEdition(event.api, {
      rowIndex: event.rowIndex,
      column: event.column,
      rowPinned: undefined
    });
  }
  isElementResize(e) {
    return e['target'] && e['target'].getAttribute('ref') === 'eResize';
  }
  isUIEvent(source, type) {
    let optionsArr = ['uiColumnMoved', 'uiColumnResized', 'uiColumnDragged', 'uiColumnExpanded', 'uiColumnSorted'];
    if (type === 'dragStopped') {
      return true;
    }
    if (source) {
      return optionsArr.includes(source);
    }
    return false;
  }
  onSelectionChange(event) {
    var _a, _b;
    const selectedRowId = (_b = (_a = event.api.getSelectedNodes()) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.id;
    const isNewRecord = this._dataUnit.isNewRecord(selectedRowId);
    if (!this._selectionChangeCallback)
      return;
    clearTimeout(this._selectionChangeDeboucing);
    this._selectionChangeDeboucing = window.setTimeout(async () => {
      const saveSuccess = (!isNewRecord && selectedRowId) ? await this.handleExecuteProceedAutosave() : true;
      if (!saveSuccess)
        return;
      this.processBuildSelectionChangeCallback(event);
    }, 0);
  }
  async handleExecuteProceedAutosave() {
    if (this._gridShowDom) {
      return await this._editionManager.proceedAutoSave();
    }
    return true;
  }
  processBuildSelectionChangeCallback(event) {
    if (this._dataUnit) {
      this.handleBuildSelectionChangeWithDU(event.context.selectionChangeQuietly);
      return;
    }
    this.buildSelectionChangeCallback(this._gridOptions.api.getSelectedRows());
  }
  handleBuildSelectionChangeWithDU(quietly) {
    if (quietly) {
      this.buildSelectionChangeCallback(this._dataUnit.records);
      return;
    }
    this._dataUnit.updatePageSelection(this._gridOptions.api.getSelectedRows()
      .map((r) => r.__record__id__))
      .then(selectionInfo => this.buildSelectionChangeCallback(selectionInfo.records));
  }
  buildSelectionChangeCallback(records) {
    this._selectionChangeCallback({
      selection: records,
      selectionHeaderStatus: this.getSelectionHeaderStatus(),
    });
  }
  onRowDoubleClick(evt) {
    var _a, _b;
    if (this._doubleClickCallBack && (!this._options.enableGridInsert || !this._dataUnit.hasNewRecord())) {
      /**
       * Evita mudança de view e a grade permanecer no modo de edição.
       */
      (_b = (_a = this._gridOptions) === null || _a === void 0 ? void 0 : _a.api) === null || _b === void 0 ? void 0 : _b.stopEditing();
      this._doubleClickCallBack(evt.data);
    }
  }
  conditionalSet(host, attribute, value) {
    if (value !== null && value !== undefined && value !== false) {
      host[attribute] = value;
    }
  }
  processEditionCanceled() {
    this.clearInvalidCells(true);
    if (this._gridShowDom) {
      this._dataUnit.clearSelection();
    }
  }
  setCellEditors(customEditors) {
    var _a, _b, _c, _d, _e;
    if (!this._editionManager) {
      this._customEditors = customEditors;
      return;
    }
    const currentEditingCells = (_b = (_a = this._gridOptions) === null || _a === void 0 ? void 0 : _a.api) === null || _b === void 0 ? void 0 : _b.getEditingCells();
    this._editionManager.setCellEditors(customEditors);
    if ((currentEditingCells === null || currentEditingCells === void 0 ? void 0 : currentEditingCells.length) > 0) {
      this._gridOptions.api.startEditingCell({ colKey: (_d = (_c = currentEditingCells[0]) === null || _c === void 0 ? void 0 : _c.column) === null || _d === void 0 ? void 0 : _d.getColId(), rowIndex: (_e = currentEditingCells[0]) === null || _e === void 0 ? void 0 : _e.rowIndex });
    }
  }
  setCellRenders(customRenders) {
    var _a, _b, _c, _d, _e, _f;
    if (!this._editionManager) {
      this._customRenders = customRenders;
      return;
    }
    this._editionManager.setCellRenders(customRenders);
    const currentEditingCells = (_b = (_a = this._gridOptions) === null || _a === void 0 ? void 0 : _a.api) === null || _b === void 0 ? void 0 : _b.getEditingCells();
    (_c = this._gridOptions) === null || _c === void 0 ? void 0 : _c.api.redrawRows();
    if ((currentEditingCells === null || currentEditingCells === void 0 ? void 0 : currentEditingCells.length) > 0) {
      this._gridOptions.api.startEditingCell({ colKey: (_e = (_d = currentEditingCells[0]) === null || _d === void 0 ? void 0 : _d.column) === null || _e === void 0 ? void 0 : _e.getColId(), rowIndex: (_f = currentEditingCells[0]) === null || _f === void 0 ? void 0 : _f.rowIndex });
    }
  }
  clearInvalidCells(stopEdition) {
    if (!this._editionManager)
      return;
    this._editionManager.clearInvalidCells(stopEdition);
    this._gridOptions.api.refreshCells({ force: true });
  }
  processContinuousInsert() {
    this._editionManager.processContinuousInsert();
  }
  destroy() {
    var _a;
    this.observer.disconnect();
    (_a = this._dataSource) === null || _a === void 0 ? void 0 : _a.destroy();
  }
  registryListeners() {
    var _a;
    (_a = this._dataSource) === null || _a === void 0 ? void 0 : _a.registryListeners();
  }
  resetPaginationState() {
    var _a, _b;
    (_b = (_a = this._gridOptions) === null || _a === void 0 ? void 0 : _a.api) === null || _b === void 0 ? void 0 : _b.clearRangeSelection();
  }
  stopEdit() {
    this._gridOptions.api.stopEditing();
  }
  getColumnWidth(cfgColumn) {
    var _a, _b, _c, _d, _e, _f;
    if (cfgColumn == undefined) {
      return;
    }
    if (cfgColumn.customWidth != undefined) {
      return cfgColumn.customWidth;
    }
    if (cfgColumn.width != undefined && !isNaN(cfgColumn.width)) {
      const parseWidth = parseInt(cfgColumn.width);
      // TODO: Valor somado devido a divergência do tamanho das fontes entre HTML5 e Design System.
      if (parseWidth > 0)
        return parseWidth + this.DEFAULT_FONT_SIZE_HTML5;
    }
    const field = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.getField(cfgColumn.name);
    const label = (_b = field === null || field === void 0 ? void 0 : field.label) !== null && _b !== void 0 ? _b : (_f = (_e = (_d = (_c = this._gridOptions) === null || _c === void 0 ? void 0 : _c.columnApi) === null || _d === void 0 ? void 0 : _d.getColumn(cfgColumn.name)) === null || _e === void 0 ? void 0 : _e.getColDef()) === null || _f === void 0 ? void 0 : _f.headerName;
    if ((field === null || field === void 0 ? void 0 : field.userInterface) === UserInterface.SEARCH) {
      return this.DEFAULT_MAX_SIZE;
    }
    return this.getColumnWidthByLabel(label);
  }
  getColumnWidthByLabel(label) {
    const labelSize = ((label === null || label === void 0 ? void 0 : label.length) || 0) * this.DEFAULT_FONT_SIZE + this.DEFAULT_ICON_SIZE;
    return labelSize > this.DEFAULT_MAX_SIZE ? this.DEFAULT_MAX_SIZE : labelSize;
  }
  getCodeColFromDescriptionCol(descriptionColName) {
    var _a;
    const colGrid = this._gridOptions.columnApi.getColumn(descriptionColName);
    const colDef = colGrid === null || colGrid === void 0 ? void 0 : colGrid.getColDef();
    return (_a = colDef === null || colDef === void 0 ? void 0 : colDef.headerComponentParams) === null || _a === void 0 ? void 0 : _a.presentationFrom;
  }
}
