import { Action as DUAction, ApplicationContext, DataType, ElementIDUtils, KeyboardManager, ObjectUtils, StringUtils, UserInterface, } from '@sankhyalabs/core';
import { CSSVarsUtils } from '@sankhyalabs/ezui/dist/collection/utils';
import { h } from '@stencil/core';
import { SIMPLE_CRUD_MODE, VIEW_MODE } from '../../lib/utils/constants';
import { TaskbarElement } from '../snk-taskbar/elements/taskbar-elements';
import { CrudUtils, FormConfigFetcher, PresentationMode } from '../../lib';
import TaskbarProcessor from '../snk-taskbar/processor/taskbar-processor';
import InMemoryLoader from '../../lib/dataUnit/InMemoryLoader';
import SnkMultiSelectionListDataSource from '../snk-grid/filtercolumn/SnkMultiSelectionListDataSource';
import { ConfigStorage } from '../../lib/configs/ConfigStorage';
import { SnkFormConfigManager } from '../snk-form-config/SnkFormConfigManager';
import { REGULAR_DEFAULT_BTNS, REGULAR_SELECTED_BTNS } from './snk-simple-crud.constants';
import RmPrecisionCustomValueFormatter from '../../lib/DefaultCustomFormatters/RmPrecisionCustomValueFormatter';
import ClientSideExporterProvider from '../snk-data-exporter/providers/ClientSideExporterProvider';
import store from '../../lib/store';
import { ContinuousInsertUtils } from '../../lib/utils/ContinuousInsertUtils';
import { buildFieldSearch } from '@sankhyalabs/ezui/dist/collection/utils';
export class SnkSimpleCrud {
  constructor() {
    this._multiSelectionListDataSource = new SnkMultiSelectionListDataSource();
    this._formConfigFetcher = new FormConfigFetcher();
    this._customEditors = new Map();
    this._customRenders = new Map();
    this._container = undefined;
    this._showPopUpGridConfig = false;
    this._currentViewMode = VIEW_MODE.GRID;
    this._config = undefined;
    this._fieldToGetFocus = undefined;
    this._customContainerId = `SNK-SIMPLE-CRUD-CUSTOM-CONTAINER-${StringUtils.generateUUID()}`;
    this.enableLockManagerLoadingComp = false;
    this.enableLockManagerTaskbarClick = false;
    this.dataState = undefined;
    this.dataUnit = undefined;
    this.entityName = undefined;
    this.mode = SIMPLE_CRUD_MODE.SERVER;
    this.gridConfig = undefined;
    this.formConfig = undefined;
    this._formFields = [];
    this._fieldsProps = new Map();
    this.enableContinuousInsert = false;
    this.multipleSelection = undefined;
    this.useCancelConfirm = true;
    this.pageSize = 150;
    this.resourceID = undefined;
    this.enableGridInsert = false;
    this.paginationCounterMode = 'auto';
    this.taskbarManager = undefined;
    this.messagesBuilder = undefined;
    this.useEnterLikeTab = false;
    this.actionsList = undefined;
    this.configName = undefined;
    this.showConfiguratorButtons = false;
    this.gridLegacyConfigName = undefined;
    this.formLegacyConfigName = undefined;
    this.ignoreReadOnlyFormFields = false;
    this.autoFocus = true;
    this.domainMessagesBuilder = undefined;
    this.multipleEditionEnabled = true;
    this.layoutFormConfig = true;
    this.disableGridEdition = false;
    this.autoLoad = undefined;
    this.outlineMode = false;
  }
  /**
   * @description Registra um editor customizado para campos da grade e do formulário.
   * @param {string} fieldName - O nome do campo.
   * @param {ICustomEditor} customEditor - A instância do editor customizado.
   * @returns {Promise<void>}
   */
  async addCustomEditor(fieldName, customEditor) {
    if (this._grid && this._form) {
      this._grid.addCustomEditor(fieldName, customEditor);
      this._form.addCustomEditor(fieldName, customEditor);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, customEditor);
    this._customEditors = newCustomEditors;
  }
  /**
   * @description Registra um renderizador customizado para colunas da grade.
   * @param {string} fieldName - O nome do campo.
   * @param {ICustomRender} customRender - A instância do renderizador customizado.
   * @returns {Promise<void>}
   */
  async addGridCustomRender(fieldName, customRender) {
    if (this._grid) {
      this._grid.addGridCustomRender(fieldName, customRender);
      return;
    }
    const newCustomRenders = new Map(this._customRenders);
    newCustomRenders.set(fieldName, customRender);
    this._customRenders = newCustomRenders;
  }
  async handleResourceIDChanged(newValue, oldValue) {
    if (StringUtils.isEmpty(newValue)) {
      return;
    }
    if (newValue === oldValue) {
      return;
    }
    await this.loadFormConfig(true);
    await this.loadGridConfig(true);
  }
  /**
   * @description Registra um formatador de valores para uma coluna da grade.
   * @param {string} columnName - O nome da coluna.
   * @param {ICustomFormatter} customFormatter - A instância do formatador customizado.
   * @returns {Promise<void>}
   */
  async addCustomValueFormatter(columnName, customFormatter) {
    this._grid.addCustomValueFormatter(columnName, customFormatter);
  }
  /**
   * @description Remove o formatador de valores de uma coluna da grade.
   * @param {string} columnName - O nome da coluna.
   * @returns {Promise<void>}
   */
  async removeCustomValueFormatter(columnName) {
    this._grid.removeCustomValueFormatter(columnName);
  }
  /**
   * @description Altera/adiciona uma propriedade nos metadados do campo.
   * @param {string} fieldName - O nome do campo.
   * @param {string} propName - O nome da propriedade.
   * @param {any} value - O valor da propriedade.
   * @returns {Promise<void>}
   */
  async setFieldProp(fieldName, propName, value) {
    const newCustomFieldProps = new Map(this._fieldsProps);
    const currentProps = this._fieldsProps.get(fieldName);
    newCustomFieldProps.set(fieldName, Object.assign(Object.assign({}, currentProps), { [propName]: value }));
    this._fieldsProps = newCustomFieldProps;
  }
  loadTaskbarProcessor() {
    const taskbarIDs = {};
    taskbarIDs[TASKBAR_ID.FORM_REGULAR] = this.getButtons(false, [TaskbarElement.GRID_MODE], true);
    taskbarIDs[TASKBAR_ID.GRID_REGULAR] = this.getButtons(false, [TaskbarElement.DATA_EXPORTER, TaskbarElement.FORM_MODE]);
    taskbarIDs[TASKBAR_ID.FORM_SELECTED] = this.getButtons(true, [TaskbarElement.GRID_MODE], true);
    taskbarIDs[TASKBAR_ID.GRID_SELECTED] = this.getGridSelectedButtonsCallBack.bind(this);
    taskbarIDs[TASKBAR_ID.FINISH_EDITION] = this.getFinishEditionButtonsCallback.bind(this);
    taskbarIDs[TASKBAR_ID.MULTIPLE_EDITION] = [TaskbarElement.CANCEL];
    this._taskbarProcessor = new TaskbarProcessor(taskbarIDs);
  }
  getGridSelectedButtonsCallBack() {
    var _a, _b, _c;
    if (!this.multipleEditionEnabled || ((_c = (_b = (_a = this.dataState) === null || _a === void 0 ? void 0 : _a.selectionInfo) === null || _b === void 0 ? void 0 : _b.records) === null || _c === void 0 ? void 0 : _c.length) === 1) {
      return this.getButtons(true, [TaskbarElement.DATA_EXPORTER, TaskbarElement.FORM_MODE]);
    }
    return this.getButtons(true, [TaskbarElement.UPDATE_MULTIPLE, TaskbarElement.DATA_EXPORTER, TaskbarElement.FORM_MODE]);
  }
  getFinishEditionButtonsCallback() {
    const btns = [TaskbarElement.CANCEL, TaskbarElement.SAVE];
    if (this.enableGridInsert && this._currentViewMode !== VIEW_MODE.ATTACHMENT) {
      btns.push(this._currentViewMode === VIEW_MODE.GRID ? TaskbarElement.FORM_MODE : TaskbarElement.GRID_MODE);
    }
    return btns;
  }
  getButtons(selected, extraButtons, removeRefresh) {
    let btnList = selected ? REGULAR_SELECTED_BTNS : REGULAR_DEFAULT_BTNS;
    if (removeRefresh || this.mode === SIMPLE_CRUD_MODE.IN_MEMORY) {
      btnList = btnList.filter(item => item !== TaskbarElement.REFRESH);
    }
    return this.addConfigButton(btnList.concat(extraButtons));
  }
  addConfigButton(buttons) {
    if (this.configName === undefined || (this.configName && this.gridLegacyConfigName)) {
      return buttons;
    }
    return buttons.concat(TaskbarElement.CONFIGURATOR);
  }
  get application() {
    return ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  /**
   * @description Usado para alternar a visão entre GRID e FORM externamente.
   * @param {VIEW_MODE} view - A visão para a qual navegar.
   * @returns {Promise<void>}
   */
  async goToView(view) {
    this._currentViewMode = view;
    if (this._viewStack) {
      if (view === VIEW_MODE.GRID)
        this.dataUnit.isMultipleEdition = false;
      this._viewStack.show(view);
    }
    if (view === VIEW_MODE.GRID) {
      requestAnimationFrame(() => this.focusToGrid());
    }
    if (view === VIEW_MODE.FORM) {
      requestAnimationFrame(() => this.focusToForm());
    }
  }
  actionClickListener(evt) {
    this.handleTaskbarAction(evt.detail);
    evt.stopPropagation();
  }
  handleTaskbarAction(action) {
    switch (action) {
      case TaskbarElement.CONFIGURATOR:
        this._snkConfigurator.open();
        break;
      case TaskbarElement.GRID_MODE:
        this.goToView(VIEW_MODE.GRID);
        break;
      case TaskbarElement.FORM_MODE:
        this.goToView(VIEW_MODE.FORM);
        break;
      case TaskbarElement.UPDATE_MULTIPLE:
        this.dataUnit.isMultipleEdition = true;
        this.goToView(VIEW_MODE.FORM);
        break;
    }
  }
  async onChangeEntityName(newValue) {
    if (this.dataUnit)
      return;
    const application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this.dataUnit = await application.getDataUnit(newValue, null, null, this.configName);
  }
  onModeChange() {
    if (this.mode == SIMPLE_CRUD_MODE.IN_MEMORY) {
      this.initInMemoryDataUnit();
    }
  }
  observeDataState(newValue, oldValue) {
    this.handleDataStateChange(newValue, oldValue);
  }
  async observeFormLegacy(newValue, oldValue) {
    await this.handleUpdateFormLegacyConfig(newValue, oldValue);
  }
  async observeGridLegacy(newValue, oldValue) {
    await this.handleUpdateGridLegacyConfig(newValue, oldValue);
  }
  async handleDataStateChange(newValue, oldValue) {
    if (ObjectUtils.objectToString(oldValue) != ObjectUtils.objectToString(newValue)) {
      this.dataStateChange.emit(newValue);
    }
    await this.processRmPrecision();
  }
  async processRmPrecision() {
    var _a, _b;
    const fieldsWithRmPrecision = await this._snkDataUnit.getFieldsWithRmPrecision();
    for (const field of fieldsWithRmPrecision || []) {
      if (!field) {
        continue;
      }
      const rmPrecision = (_b = (_a = this.dataState) === null || _a === void 0 ? void 0 : _a.rowMetadata) === null || _b === void 0 ? void 0 : _b.getProp('rm_precision', field);
      if (!rmPrecision && rmPrecision !== 0) {
        continue;
      }
      await this.setFieldProp(field, 'precision', rmPrecision);
      await this.setFieldProp(field, 'prettyPrecision', rmPrecision);
    }
    this._rmPrecisionCustomValueFormatter.setDataState(this.dataState);
  }
  async handleUpdateGridLegacyConfig(newValue, oldValue) {
    if (newValue == undefined || newValue == oldValue) {
      return;
    }
    if (!this._gridConfigAlreadyLoaded) {
      return;
    }
    await this.loadGridConfig(true);
  }
  async handleUpdateFormLegacyConfig(newValue, oldValue) {
    if (newValue == undefined || newValue == oldValue) {
      return;
    }
    if (!this._formConfigAlreadyLoaded) {
      return;
    }
    await this.loadFormConfig(true);
  }
  openConfig(viewMode) {
    this._snkConfigurator.close();
    if (viewMode === VIEW_MODE.GRID) {
      this.openGridConfig();
    }
    else if (viewMode === VIEW_MODE.FORM) {
      this.openFormConfig();
    }
  }
  openGridConfig() {
    this._grid.getColumnsState()
      .then((gridColumns) => {
      this._snkGridConfig.columns = gridColumns.filter(c => c.name);
      this._snkGridConfig.selectedIndex = 0;
      this._showPopUpGridConfig = true;
    });
  }
  async openFormConfig() {
    if (this.formLegacyConfigName || this.configName) {
      await this._snkSimpleFormConfig.show();
    }
  }
  addGridLegacyConfigName() {
    if (this.gridLegacyConfigName && this.configName) {
      ConfigStorage.addGridLegacyConfig(this.configName, this.gridLegacyConfigName);
    }
  }
  loadGridConfig(forceUpdate) {
    if (this.configName === undefined) {
      return;
    }
    if ((this.gridConfig != undefined || this._gridConfigAlreadyLoaded) && !forceUpdate) {
      return;
    }
    this.addGridLegacyConfigName();
    this._gridConfigAlreadyLoaded = true;
    return new Promise((accept, reject) => {
      ConfigStorage.loadGridConfig(this.configName, this.resolveResourceID())
        .then(config => {
        this.setGridConfig(config);
        accept();
      })
        .catch(reason => {
        reject(reason);
      });
    });
  }
  formConfigIsLoaded() {
    return this.formConfig != undefined || this._formConfigAlreadyLoaded;
  }
  async loadFormConfig(forceLoad = false, forceSetNewConfig = false) {
    if (this.configName === undefined) {
      return;
    }
    if (this._formConfigManager == undefined) {
      this._formConfigManager = new SnkFormConfigManager(this.configName, this.resolveResourceID(), undefined, this.dataUnit);
      this._formConfigManager.setConfig(this.formConfig);
    }
    if (this.formConfigIsLoaded() && !forceLoad) {
      return;
    }
    this._formConfigAlreadyLoaded = true;
    let loadedLegacyConfig = await this._formConfigFetcher.fetchLegacyConfigurableForm(this.formLegacyConfigName);
    if (loadedLegacyConfig != undefined) {
      this._formConfigManager.setConfig(loadedLegacyConfig);
      this.setFormConfig(loadedLegacyConfig, forceSetNewConfig);
      return;
    }
    this.setFormConfig(await this._formConfigManager.loadConfig());
  }
  async componentWillRender() {
    this.loadTaskbarProcessor();
    this._resourceID = await this.application.getResourceID();
    this.dataExporterProviderStore();
    this.dataExporterProviderStore();
    this._taskbarProcessor.process(this.getTaskBarId(), this.taskbarManager, this.dataState, this.getTaskBarDisabledButtons());
    if (this.configName === undefined) {
      return;
    }
    if (this.gridConfig != undefined || this._gridConfigAlreadyLoaded) {
      return;
    }
    await this.addGridLegacyConfigName();
    await this.loadGridConfig();
    await this.loadFormConfig();
  }
  componentDidRender() {
    this._rmPrecisionCustomValueFormatter.setGrid(this._grid);
    this.addGridCustomValueFormattters();
    this.setFieldsProps();
    this.setCustomRenders();
    this.setCustomEditors();
  }
  componentWillLoad() {
    this.processMetadata();
    this.onModeChange();
    this.configDatasource();
    this._rmPrecisionCustomValueFormatter = new RmPrecisionCustomValueFormatter();
    this._continuousInsertUtils = new ContinuousInsertUtils(this.application, this.resolveResourceID(), this.configName);
    if (this.enableGridInsert) {
      this._continuousInsertUtils.getConfig().then(value => this.enableContinuousInsert = value);
    }
  }
  componentDidLoad() {
    CSSVarsUtils.applyVarsGrid(this._element, this._grid);
    this.initKeyboardManager();
    this.dataUnit.subscribe(this.dataUnitActionHandler.bind(this));
  }
  async dataUnitActionHandler(action) {
    if (action.type === DUAction.EDITION_CANCELED || action.type === DUAction.DATA_SAVED) {
      if (this.dataUnit.isMultipleEdition) {
        this.goToView(VIEW_MODE.GRID);
      }
    }
  }
  getMessage(key, params) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
  }
  disconnectedCallback() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  setCustomRenders() {
    if (!this._grid) {
      return;
    }
    for (const [fieldName, customRender] of this._customRenders) {
      this._grid.addGridCustomRender(fieldName, customRender);
      this._customRenders.delete(fieldName);
    }
  }
  setCustomEditors() {
    if (!this._grid || !this._form) {
      return;
    }
    for (const [fieldName, customEditor] of this._customEditors) {
      this._grid.addCustomEditor(fieldName, customEditor);
      this._form.addCustomEditor(fieldName, customEditor);
      this._customEditors.delete(fieldName);
    }
  }
  configDatasource() {
    this._multiSelectionListDataSource.setApplication(this.application);
    this._multiSelectionListDataSource.setDataUnit(this.dataUnit);
  }
  setFieldsProps() {
    if (!this._form) {
      return;
    }
    for (const [fieldName, props] of this._fieldsProps) {
      for (const prop in props) {
        this._form.setFieldProp(fieldName, prop, props[prop]);
      }
      this._fieldsProps.delete(fieldName);
    }
  }
  getTaskBarId() {
    var _a, _b;
    if ((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.isDirty) {
      return TASKBAR_ID.FINISH_EDITION;
    }
    if (this.dataUnit.isMultipleEdition) {
      return TASKBAR_ID.MULTIPLE_EDITION;
    }
    if (((_b = this.dataState) === null || _b === void 0 ? void 0 : _b.selectionInfo) &&
      !this.dataState.selectionInfo.isAllRecords() &&
      this.dataState.selectionInfo.length > 0) {
      return this._currentViewMode === VIEW_MODE.GRID ? TASKBAR_ID.GRID_SELECTED : TASKBAR_ID.FORM_SELECTED;
    }
    return this._currentViewMode === VIEW_MODE.GRID ? TASKBAR_ID.GRID_REGULAR : TASKBAR_ID.FORM_REGULAR;
  }
  initInMemoryDataUnit() {
    this._inMemoryLoader = new InMemoryLoader(this._metadata, undefined, { autoLoad: this.autoLoad });
    this.dataUnit = this._inMemoryLoader.dataUnit;
    this.dataUnitReady.emit(this.dataUnit);
  }
  /**
   * @description Define os metadados do DataUnit.
   * @param {UnitMetadata} metadata - Os metadados a serem definidos.
   * @returns {Promise<void>}
   */
  setMetadata(metadata) {
    if (this._inMemoryLoader) {
      this._inMemoryLoader.metadata = metadata;
    }
    else if (this.dataUnit) {
      this.dataUnit.metadata = metadata;
    }
    return Promise.resolve();
  }
  /**
   * @description Define os registros do DataUnit.
   * @param {Array<Record>} records - Os registros a serem definidos.
   * @returns {Promise<void>}
   */
  setRecords(records) {
    if (this._inMemoryLoader) {
      this._inMemoryLoader.records = records;
    }
    else if (this.dataUnit) {
      this.dataUnit.records = records;
    }
    return Promise.resolve();
  }
  /**
   * @description Obtém os registros do DataUnit.
   * @returns {Promise<Array<Record>>} Uma promessa que resolve com a lista de registros.
   */
  getRecords() {
    return Promise.resolve(this.dataUnit.records);
  }
  /**
   * @description Usado para abrir o configurador do CRUD.
   * @returns {Promise<void>}
   */
  async openConfigurator() {
    var _a;
    (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.open();
  }
  /**
   * @description Usado para fechar o configurador do CRUD.
   * @returns {Promise<void>}
   */
  async closeConfigurator() {
    var _a;
    (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.close();
  }
  /**
   * @description Atualiza a configuração do formulário.
   * @returns {Promise<void>}
   */
  async updateConfig() {
    if (this._formConfigManager == undefined) {
      this._formConfigManager = new SnkFormConfigManager(this.configName, this.resolveResourceID());
    }
    this._formConfigManager.setConfig(this.formConfig);
  }
  processMetadata() {
    const fieldsMetadataElem = this._element.querySelectorAll("snk-field-metadata");
    const fieldMetadata = [];
    const formConfig = { fields: [], emptyConfig: false };
    fieldsMetadataElem.forEach(fieldElem => {
      const field = {
        name: fieldElem.getAttribute("name") || fieldElem.getAttribute("label"),
        label: fieldElem.getAttribute("label"),
        dataType: DataType[fieldElem.getAttribute("dataType")] || DataType.TEXT,
        userInterface: UserInterface[fieldElem.getAttribute("userInterface")] || UserInterface.SHORTTEXT,
        readOnly: fieldElem.getAttribute("readOnly") == "true",
        required: fieldElem.getAttribute("required") == "true",
        tab: fieldElem.getAttribute("tab") || undefined,
        visible: fieldElem.getAttribute("visible") != "false"
      };
      const fieldConfig = { name: field.name, tab: field.tab, visible: field.visible };
      formConfig.fields.push(fieldConfig);
      fieldMetadata.push(field);
    });
    if (fieldMetadata.length > 0) {
      if (!this.formConfig) {
        this.formConfig = formConfig;
      }
      this._metadata = {
        name: "SimpleCrud",
        label: "SimpleCrud",
        fields: fieldMetadata
      };
    }
  }
  addGridCustomValueFormattters() {
    var _a, _b, _c;
    const metadataFields = ((_a = this._metadata) === null || _a === void 0 ? void 0 : _a.fields) || ((_c = (_b = this.dataUnit) === null || _b === void 0 ? void 0 : _b.metadata) === null || _c === void 0 ? void 0 : _c.fields);
    if (!metadataFields) {
      return;
    }
    const fieldsWithRmPrecision = [];
    metadataFields.forEach((field) => {
      var _a;
      if (((_a = field.properties) === null || _a === void 0 ? void 0 : _a.rm_precision) && !fieldsWithRmPrecision.includes(field.name)) {
        fieldsWithRmPrecision.push(field.name);
      }
    });
    fieldsWithRmPrecision.forEach(field => {
      this.addCustomValueFormatter(field, this._rmPrecisionCustomValueFormatter);
    });
  }
  onDataStateChange(evt) {
    this.dataState = Object.assign({}, evt.detail);
  }
  getTaskBarDisabledButtons() {
    var _a, _b, _c, _d, _e, _f;
    const disabledButtons = [];
    if (!((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.hasNext)) {
      disabledButtons.push(TaskbarElement.NEXT);
    }
    if (!((_b = this.dataState) === null || _b === void 0 ? void 0 : _b.hasPrevious)) {
      disabledButtons.push(TaskbarElement.PREVIOUS);
    }
    if ((_d = (_c = this.dataState) === null || _c === void 0 ? void 0 : _c.selectionInfo) === null || _d === void 0 ? void 0 : _d.isEmpty()) {
      disabledButtons.push(TaskbarElement.FORM_MODE);
    }
    if (((_f = (_e = this.dataState) === null || _e === void 0 ? void 0 : _e.selectionInfo) === null || _f === void 0 ? void 0 : _f.length) > 1) {
      disabledButtons.push(TaskbarElement.CLONE);
    }
    return disabledButtons;
  }
  handleCancelEdit() {
    var _a;
    if ((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.recordsIsEmpty) {
      this.goToView(VIEW_MODE.GRID);
      this.dataUnit.clearSelection();
    }
  }
  handleConfiguratorEvent(evt, type) {
    evt.stopImmediatePropagation();
    if (type === 'SAVE') {
      this.configuratorSave.emit();
      return;
    }
    this.configuratorCancel.emit();
  }
  onSelectField(option) {
    if (option == undefined) {
      return;
    }
    this._fieldToGetFocus = option.value;
  }
  getFieldSearch(splitButton, item) {
    if (this._fieldSearch != undefined) {
      return this._fieldSearch;
    }
    this._splitButtonForm = splitButton;
    this._fieldSearch = buildFieldSearch(item, ({ argument }) => this.fieldsOptionLoader(argument), (option) => this.onSelectField(option));
    return this._fieldSearch;
  }
  getFormFields() {
    var _a, _b;
    return (_b = (_a = this.formConfig) === null || _a === void 0 ? void 0 : _a.fields) !== null && _b !== void 0 ? _b : this._formFields;
  }
  handleFormSetFields(fields) {
    if (!ObjectUtils.equals(this._formFields, fields)) {
      this._formFields = fields !== null && fields !== void 0 ? fields : [];
    }
  }
  fieldsOptionLoader(argument) {
    const searchTerm = argument === null || argument === void 0 ? void 0 : argument.toLowerCase();
    const allFields = this.getFormFields().map(field => { var _a; return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getField(field.name); });
    const filteredFields = allFields.filter(field => {
      var _a, _b;
      return ((_a = field.name) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(searchTerm)) ||
        ((_b = field.label) === null || _b === void 0 ? void 0 : _b.toLowerCase().includes(searchTerm));
    });
    const options = filteredFields.map(field => ({ value: field.name, label: field.label }));
    return Promise.resolve(options);
  }
  isGridInsertActive() {
    return this.enableGridInsert && this.dataUnit.hasNewRecord();
  }
  getColumnSearch(splitButton, item) {
    if (this._columnSearch != undefined) {
      return this._columnSearch;
    }
    this._splitButton = splitButton;
    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);
  }
  getSettingsListGrid() {
    const hardList = [{
        value: StringUtils.generateUUID(),
        label: this.getMessage("snkSimpleCrud.findColumn"),
        disableCloseOnSelect: true,
        eagerInitialize: true,
        itemBuilder: (splitButton, item) => this.getColumnSearch(splitButton, item)
      }];
    return hardList;
  }
  getSettingsListForm() {
    const hardList = [{
        value: StringUtils.generateUUID(),
        label: this.getMessage("snkSimpleCrud.findFields"),
        disableCloseOnSelect: true,
        eagerInitialize: true,
        itemBuilder: (splitButton, item) => this.getFieldSearch(splitButton, item)
      }];
    return hardList;
  }
  getTopTaskBarId() {
    var _a;
    return ((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.isDirty) ? `snkGridTopTaskbar.finish_edition${PresentationMode.PRIMARY}` :
      `snkGridTopTaskbar.regular${PresentationMode.PRIMARY}`;
  }
  clearFieldToFocusHandler() {
    this._fieldToGetFocus = undefined;
  }
  gridConfigChangeHandler(evt) {
    evt.stopPropagation();
    if (!this.configName)
      return;
    const config = evt.detail;
    ConfigStorage.saveGridConfig(config, this.configName, this.resolveResourceID());
  }
  modalConfigChangeHandler(evt) {
    const config = evt.detail;
    this._grid.setColumnsState(config.columns)
      .then(() => {
      this.setGridConfig(config);
      this.closeGridConfig();
      this.dataExporterProviderStore();
    });
    evt.stopPropagation();
  }
  async dataExporterProviderStore() {
    if (this.dataUnit == undefined) {
      return;
    }
    if (this._grid == undefined) {
      return;
    }
    const dataExporterProvider = new ClientSideExporterProvider(this.dataUnit, this._grid);
    store.set("exporterProviders", Object.assign(Object.assign({}, store.get("exporterProviders")), { [this.getDataExporterStoreKey()]: dataExporterProvider }));
  }
  getDataExporterStoreKey() {
    return `SnkSimpleCrudDataExporter:${this.configName == undefined ? this.dataUnit.name : this.configName}`;
  }
  setGridConfig(config) {
    this.gridConfig = config;
    CrudUtils.assertDefaultSorting(this.gridConfig, this.dataUnit);
  }
  setFormConfig(config, forceUpdate) {
    if (this.formConfig && !forceUpdate)
      return;
    this.formConfig = config;
  }
  closeGridConfig() {
    this._showPopUpGridConfig = false;
  }
  getPageSize() {
    if (this.mode === SIMPLE_CRUD_MODE.IN_MEMORY) {
      return 0;
    }
    if (this.pageSize == undefined) {
      return 150;
    }
    return this.pageSize;
  }
  resolveResourceID() {
    return StringUtils.isEmpty(this.resourceID) ? this._resourceID : this.resourceID;
  }
  getFormConfig() {
    var _a;
    const configFromManager = (_a = this._formConfigManager) === null || _a === void 0 ? void 0 : _a.getConfig(this.dataUnit, this.ignoreReadOnlyFormFields);
    if (!this.configName && !configFromManager) {
      return this.formConfig;
    }
    return configFromManager;
  }
  updateFormConfig() {
    let newConfig = this.formConfig;
    if (this.formLegacyConfigName == undefined) {
      newConfig = Object.assign(Object.assign({}, this.formConfig), { fields: this.dataUnit.metadata.fields });
    }
    this.setFormConfig(newConfig, true);
    if (this._formConfigManager == undefined) {
      this._formConfigManager = new SnkFormConfigManager(this.configName, this.resolveResourceID());
    }
    this._formConfigManager.setConfig(this.formConfig);
  }
  handleDataUnitOnInsertionMode() {
    if (this.enableGridInsert)
      return;
    this.goToView(VIEW_MODE.FORM);
  }
  async initKeyboardManager() {
    var _a;
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element });
    const dataUnit = this.dataUnit || await ((_a = this._snkDataUnit) === null || _a === void 0 ? void 0 : _a.getDataUnit());
    if (dataUnit == undefined) {
      return;
    }
    this._keyboardManager
      .bind("F7", () => dataUnit.saveData(), { description: this.getMessage("snkSimpleCrud.keyboardShortcuts.saveData"), element: this._element })
      .bind("F8", dataUnit.addRecord.bind(dataUnit), { description: this.getMessage("snkSimpleCrud.keyboardShortcuts.addRecord"), element: this._element })
      .bind("F9", dataUnit.removeSelectedRecords.bind(dataUnit), { description: this.getMessage("snkSimpleCrud.keyboardShortcuts.removeRecord"), element: this._element })
      .bind("Escape", () => {
      if (dataUnit.isDirty()) {
        dataUnit.cancelEdition();
      }
    }, {
      debounceTime: 1000,
      description: this.getMessage("snkSimpleCrud.keyboardShortcuts.cancelAction"), element: this._element
    });
  }
  async handleFormConfigSaved() {
    await this.loadFormConfig(true, true);
  }
  focusToGrid() {
    const gridElement = this._grid;
    gridElement.focus();
  }
  focusToForm() {
    const formElement = this._form;
    formElement.focus();
  }
  renderTaskbarContent(layout) {
    var _a;
    return (h("snk-taskbar", { class: `ez-box--no-outline ez-box ${this._currentViewMode === VIEW_MODE.FORM ? (this.outlineMode ? 'ez-box--outline' : 'ez-box--shadow-xsmall') + ' ez-padding--small' : ''}`, dataUnit: this.dataUnit, primaryButton: ((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.isDirty) ? "SAVE" : "INSERT", "data-element-id": "grid_left", messagesBuilder: this.messagesBuilder, buttons: this._taskbarProcessor.buttons, actionsList: this.getActionsList(), actionsSettingsList: layout === VIEW_MODE.GRID ? this.getSettingsListGrid() : this.getSettingsListForm(), disabledButtons: this._taskbarProcessor.disabledButtons, customButtons: this._taskbarProcessor.customButtons, "data-exporter-store-key": this.getDataExporterStoreKey(), slot: "leftButtons", presentationMode: PresentationMode.SECONDARY, tabindex: "0" }, h("slot", { name: "TASKBAR_CUSTOM_ELEMENTS" })));
  }
  /* istanbul ignore next */
  render() {
    var _a;
    if (this.dataUnit == undefined) {
      return;
    }
    return (h("snk-data-unit", { ref: ref => this._snkDataUnit = ref, class: "simple-crud__container", dataUnit: this.dataUnit, useCancelConfirm: this.useCancelConfirm, onDataStateChange: evt => this.onDataStateChange(evt), onCancelEdition: this.handleCancelEdit.bind(this), pageSize: this.getPageSize(), onInsertionMode: this.handleDataUnitOnInsertionMode.bind(this), onDataUnitReady: (evt) => this.dataUnitReady.emit(evt.detail), onMessagesBuilderUpdated: evt => this.messagesBuilder = evt.detail, onDataUnitFieldsHidded: this.updateFormConfig.bind(this), domainMessagesBuilder: this.domainMessagesBuilder }, h("header", null, h("slot", { name: "snkSimpleCrudHeader" })), h("section", { class: `ez-box ez-box--no-outline ${this.outlineMode ? 'ez-box--outline' : 'ez-box--shadow'} simple-crud__container-section`, ref: (ref) => this._container = ref, tabindex: "0" }, h("ez-view-stack", { ref: (ref) => this._viewStack = ref, "data-element-id": "simple-crud" }, h("stack-item", null, h("ez-grid", { class: "ez-margin-bottom--large ez-box--no-outline", ref: ref => this._grid = ref, dataUnit: this.dataUnit, config: this.gridConfig, "no-header": true, multipleSelection: this.multipleSelection, onEzDoubleClick: () => this.goToView(VIEW_MODE.FORM), onConfigChange: evt => this.gridConfigChangeHandler(evt), columnfilterDataSource: this.dataUnit.name && this.dataUnit.name.includes(InMemoryLoader.IN_MEMORY_DATA_UNIT_NAME)
        ? undefined
        : this._multiSelectionListDataSource, useEnterLikeTab: this.useEnterLikeTab, autoFocus: this.autoFocus, enableGridInsert: this.enableGridInsert, enableContinuousInsert: this.enableContinuousInsert, enableLockManagerTaskbarClick: this.enableLockManagerTaskbarClick, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, outlineMode: this.outlineMode, tabindex: "0", paginationCounterMode: this.paginationCounterMode, canEdit: !this.disableGridEdition }, this.renderTaskbarContent(VIEW_MODE.GRID), h("div", { slot: "footer" }, h("slot", { name: "snkSimpleCrudFooter" })))), h("stack-item", null, this.renderTaskbarContent(VIEW_MODE.FORM), h("ez-form", { ref: (ref) => this._form = ref, class: `ez-margin-top--large  ez-box--no-outline`, dataUnit: this.dataUnit, config: this.getFormConfig(), fieldToFocus: this._fieldToGetFocus, onEzFormSetFields: (evt) => this.handleFormSetFields(evt.detail), onEzFormRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this), elementFocusSearchField: this._container, tabindex: "0" }), h("slot", { name: "snkSimpleCrudFormFooter" }), h("snk-simple-form-config", { ref: (ref) => this._snkSimpleFormConfig = ref, dataUnit: this.dataUnit, onSnkConfigSaved: this.handleFormConfigSaved.bind(this), configName: (_a = this.formLegacyConfigName) !== null && _a !== void 0 ? _a : this.configName, messagesBuilder: this.messagesBuilder })), this.messagesBuilder && h("snk-configurator", { ref: (ref) => this._snkConfigurator = ref, viewMode: this._currentViewMode, messagesBuilder: this.messagesBuilder, onConfigSelected: (evt) => this.goToView(evt.detail), onOpenConfig: (evt) => this.openConfig(evt.detail), showActionButtons: this.showConfiguratorButtons, onSave: evt => this.handleConfiguratorEvent(evt, 'SAVE'), onCancel: evt => this.handleConfiguratorEvent(evt, 'CANCEL'), resourceID: this.resolveResourceID(), customContainerId: this._customContainerId, layoutFormConfig: this.layoutFormConfig })), h("div", { id: `${this._customContainerId}` }, h("slot", { name: "SnkConfigContainerSlot" }))), h("ez-popup", { size: "medium", heightMode: "auto", useHeader: false, opened: this._showPopUpGridConfig, 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.resolveResourceID() }))));
  }
  static get is() { return "snk-simple-crud"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-simple-crud.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-simple-crud.css"]
    };
  }
  static get properties() {
    return {
      "enableLockManagerLoadingComp": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Define se o componente deve usar o LockManager para controle de carregamento da aplica\u00E7\u00E3o."
            }],
          "text": ""
        },
        "attribute": "enable-lock-manager-loading-comp",
        "reflect": false,
        "defaultValue": "false"
      },
      "enableLockManagerTaskbarClick": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Ativa o gerenciamento de locks na grade pela Taskbar."
            }],
          "text": ""
        },
        "attribute": "enable-lock-manager-taskbar-click",
        "reflect": false,
        "defaultValue": "false"
      },
      "dataState": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "DataState",
          "resolved": "DataState",
          "references": {
            "DataState": {
              "location": "import",
              "path": "../snk-data-unit/snk-data-unit"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Estado atual dos dados."
            }],
          "text": ""
        }
      },
      "dataUnit": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "DataUnit",
          "resolved": "DataUnit",
          "references": {
            "DataUnit": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Inst\u00E2ncia do DataUnit a ser utilizada pelo componente."
            }],
          "text": ""
        }
      },
      "entityName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Define o nome da entidade que o componente vai utilizar para fazer as opera\u00E7\u00F5es de CRUD."
            }],
          "text": ""
        },
        "attribute": "entity-name",
        "reflect": false
      },
      "mode": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "SIMPLE_CRUD_MODE",
          "resolved": "SIMPLE_CRUD_MODE.IN_MEMORY | SIMPLE_CRUD_MODE.SERVER",
          "references": {
            "SIMPLE_CRUD_MODE": {
              "location": "import",
              "path": "../../lib/utils/constants"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Define o modo de opera\u00E7\u00E3o do CRUD (servidor ou em mem\u00F3ria)."
            }],
          "text": ""
        },
        "attribute": "mode",
        "reflect": false,
        "defaultValue": "SIMPLE_CRUD_MODE.SERVER"
      },
      "gridConfig": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "IGridConfig",
          "resolved": "IGridConfig",
          "references": {
            "IGridConfig": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/components/ez-grid/controller/EzGridController"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Configura\u00E7\u00E3o da grade."
            }],
          "text": ""
        }
      },
      "formConfig": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "IFormConfig",
          "resolved": "IFormConfig",
          "references": {
            "IFormConfig": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils/form/interfaces"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Configura\u00E7\u00E3o do formul\u00E1rio."
            }],
          "text": ""
        }
      },
      "enableContinuousInsert": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Habilita a inser\u00E7\u00E3o cont\u00EDnua de registros."
            }],
          "text": ""
        },
        "attribute": "enable-continuous-insert",
        "reflect": false,
        "defaultValue": "false"
      },
      "multipleSelection": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Determina se pode haver mais de uma linha selecionada na grade."
            }],
          "text": ""
        },
        "attribute": "multiple-selection",
        "reflect": false
      },
      "useCancelConfirm": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Determina se ser\u00E1 usada mensagem de confirma\u00E7\u00E3o padr\u00E3o na tentativa de cancelar a edi\u00E7\u00E3o."
            }],
          "text": ""
        },
        "attribute": "use-cancel-confirm",
        "reflect": false,
        "defaultValue": "true"
      },
      "pageSize": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Determina quantas linhas s\u00E3o retornadas por p\u00E1gina."
            }],
          "text": ""
        },
        "attribute": "page-size",
        "reflect": false,
        "defaultValue": "150"
      },
      "resourceID": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Identificador de recursos como configura\u00E7\u00F5es e acesso."
            }],
          "text": ""
        },
        "attribute": "resource-i-d",
        "reflect": false
      },
      "enableGridInsert": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Ativa a inser\u00E7\u00E3o de registros no modo grade."
            }],
          "text": ""
        },
        "attribute": "enable-grid-insert",
        "reflect": false,
        "defaultValue": "false"
      },
      "paginationCounterMode": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "'show' | 'hidden' | 'auto'",
          "resolved": "\"auto\" | \"hidden\" | \"show\"",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Define o modo de exibi\u00E7\u00E3o do contador de pagina\u00E7\u00E3o."
            }],
          "text": ""
        },
        "attribute": "pagination-counter-mode",
        "reflect": false,
        "defaultValue": "'auto'"
      },
      "taskbarManager": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "TaskbarManager",
          "resolved": "TaskbarManager",
          "references": {
            "TaskbarManager": {
              "location": "import",
              "path": "../snk-taskbar/snk-taskbar"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Gerenciador das barras de tarefas. \u00C9 poss\u00EDvel determinar bot\u00F5es espec\u00EDficos ou mesmo gerenciar o estado dos bot\u00F5es."
            }],
          "text": ""
        }
      },
      "messagesBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Respons\u00E1vel por flexibilizar e padronizar o uso de mensagens nos blocos de constru\u00E7\u00E3o."
            }],
          "text": ""
        }
      },
      "useEnterLikeTab": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Quando verdadeiro, o ENTER far\u00E1 a navega\u00E7\u00E3o como se fosse a tecla TAB na grade."
            }],
          "text": ""
        },
        "attribute": "use-enter-like-tab",
        "reflect": false,
        "defaultValue": "false"
      },
      "actionsList": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Array<Action>",
          "resolved": "Action[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "Action": {
              "location": "import",
              "path": "../snk-taskbar/snk-taskbar"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "A\u00E7\u00F5es a serem colocadas no bot\u00E3o \"Mais op\u00E7\u00F5es\" do componente snk-taskbar."
            }],
          "text": ""
        }
      },
      "configName": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Usado para salvar as configura\u00E7\u00F5es dos blocos de constru\u00E7\u00E3o."
            }],
          "text": ""
        },
        "attribute": "config-name",
        "reflect": false
      },
      "showConfiguratorButtons": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Usado para exibir os bot\u00F5es de a\u00E7\u00E3o do snk-configurator."
            }],
          "text": ""
        },
        "attribute": "show-configurator-buttons",
        "reflect": false,
        "defaultValue": "false"
      },
      "gridLegacyConfigName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Chave da configura\u00E7\u00E3o legada da grade."
            }],
          "text": ""
        },
        "attribute": "grid-legacy-config-name",
        "reflect": false
      },
      "formLegacyConfigName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Chave da configura\u00E7\u00E3o legada do formul\u00E1rio."
            }],
          "text": ""
        },
        "attribute": "form-legacy-config-name",
        "reflect": false
      },
      "ignoreReadOnlyFormFields": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Ignora os campos \"somente leitura\" no modo de inser\u00E7\u00E3o."
            }],
          "text": ""
        },
        "attribute": "ignore-read-only-form-fields",
        "reflect": false,
        "defaultValue": "false"
      },
      "autoFocus": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Define se a grade ser\u00E1 focada ao ser carregada."
            }],
          "text": ""
        },
        "attribute": "auto-focus",
        "reflect": false,
        "defaultValue": "true"
      },
      "domainMessagesBuilder": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Define a chave customizada para sobrescrever as mensagens (n\u00E3o pegando pela entidade)."
            }],
          "text": ""
        },
        "attribute": "domain-messages-builder",
        "reflect": false
      },
      "multipleEditionEnabled": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Habilita a edi\u00E7\u00E3o de m\u00FAltiplos registros simult\u00E2neos."
            }],
          "text": ""
        },
        "attribute": "multiple-edition-enabled",
        "reflect": false,
        "defaultValue": "true"
      },
      "layoutFormConfig": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Define se o LayoutFormConfig ser\u00E1 exibido no configurador."
            }],
          "text": ""
        },
        "attribute": "layout-form-config",
        "reflect": false,
        "defaultValue": "true"
      },
      "disableGridEdition": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Desabilita a edi\u00E7\u00E3o na grade."
        },
        "attribute": "disable-grid-edition",
        "reflect": false,
        "defaultValue": "false"
      },
      "autoLoad": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Define se a carga dos dados ser\u00E1 feita assim que o componente for carregado."
            }],
          "text": ""
        },
        "attribute": "auto-load",
        "reflect": false
      },
      "outlineMode": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Altera visualmente as sombras e bordas do componente.\nQuando `false`, aplica o padr\u00E3o de sombras ao componente (utilizar quando for o elemento principal do layout).\nQuando `true`, aplica o padr\u00E3o de contorno ao componente (utilizar quando estiver contido em outro elemento como um painel ou pop-up)."
            }],
          "text": ""
        },
        "attribute": "outline-mode",
        "reflect": false,
        "defaultValue": "false"
      }
    };
  }
  static get states() {
    return {
      "_container": {},
      "_showPopUpGridConfig": {},
      "_currentViewMode": {},
      "_config": {},
      "_fieldToGetFocus": {},
      "_customContainerId": {},
      "_formFields": {},
      "_fieldsProps": {}
    };
  }
  static get events() {
    return [{
        "method": "dataStateChange",
        "name": "dataStateChange",
        "bubbles": false,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Emitido quando h\u00E1 qualquer mudan\u00E7a de estado no DataUnit."
            }],
          "text": ""
        },
        "complexType": {
          "original": "DataState",
          "resolved": "DataState",
          "references": {
            "DataState": {
              "location": "import",
              "path": "../snk-data-unit/snk-data-unit"
            }
          }
        }
      }, {
        "method": "dataUnitReady",
        "name": "dataUnitReady",
        "bubbles": false,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Emitido quando o DataUnit est\u00E1 pronto."
            }],
          "text": ""
        },
        "complexType": {
          "original": "DataUnit",
          "resolved": "DataUnit",
          "references": {
            "DataUnit": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        }
      }, {
        "method": "actionClick",
        "name": "actionClick",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Emitido sempre que houver clique de bot\u00E3o ou a\u00E7\u00E3o na barra de tarefas."
            }],
          "text": ""
        },
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        }
      }, {
        "method": "formItemsReady",
        "name": "formItemsReady",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Respons\u00E1vel por notificar quando ocorrer a renderiza\u00E7\u00E3o de itens do formul\u00E1rio."
            }],
          "text": ""
        },
        "complexType": {
          "original": "Array<HTMLElement>",
          "resolved": "HTMLElement[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "HTMLElement": {
              "location": "global"
            }
          }
        }
      }, {
        "method": "configuratorSave",
        "name": "configuratorSave",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Emitido quando a configura\u00E7\u00E3o no configurador do CRUD \u00E9 salva."
            }],
          "text": ""
        },
        "complexType": {
          "original": "any",
          "resolved": "any",
          "references": {}
        }
      }, {
        "method": "configuratorCancel",
        "name": "configuratorCancel",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [{
              "name": "description",
              "text": "Emitido quando o salvamento da configura\u00E7\u00E3o no configurador do CRUD \u00E9 cancelado."
            }],
          "text": ""
        },
        "complexType": {
          "original": "any",
          "resolved": "any",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "addCustomEditor": {
        "complexType": {
          "signature": "(fieldName: string, customEditor: ICustomEditor) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "fieldName - O nome do campo."
                }],
              "text": "- O nome do campo."
            }, {
              "tags": [{
                  "name": "param",
                  "text": "customEditor - A inst\u00E2ncia do editor customizado."
                }],
              "text": "- A inst\u00E2ncia do editor customizado."
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomEditor": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Registra um editor customizado para campos da grade e do formul\u00E1rio."
            }, {
              "name": "param",
              "text": "fieldName - O nome do campo."
            }, {
              "name": "param",
              "text": "customEditor - A inst\u00E2ncia do editor customizado."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "addGridCustomRender": {
        "complexType": {
          "signature": "(fieldName: string, customRender: ICustomRender) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "fieldName - O nome do campo."
                }],
              "text": "- O nome do campo."
            }, {
              "tags": [{
                  "name": "param",
                  "text": "customRender - A inst\u00E2ncia do renderizador customizado."
                }],
              "text": "- A inst\u00E2ncia do renderizador customizado."
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomRender": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Registra um renderizador customizado para colunas da grade."
            }, {
              "name": "param",
              "text": "fieldName - O nome do campo."
            }, {
              "name": "param",
              "text": "customRender - A inst\u00E2ncia do renderizador customizado."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "addCustomValueFormatter": {
        "complexType": {
          "signature": "(columnName: string, customFormatter: ICustomFormatter) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "columnName - O nome da coluna."
                }],
              "text": "- O nome da coluna."
            }, {
              "tags": [{
                  "name": "param",
                  "text": "customFormatter - A inst\u00E2ncia do formatador customizado."
                }],
              "text": "- A inst\u00E2ncia do formatador customizado."
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomFormatter": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/components/ez-grid/interfaces"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Registra um formatador de valores para uma coluna da grade."
            }, {
              "name": "param",
              "text": "columnName - O nome da coluna."
            }, {
              "name": "param",
              "text": "customFormatter - A inst\u00E2ncia do formatador customizado."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "removeCustomValueFormatter": {
        "complexType": {
          "signature": "(columnName: string) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "columnName - O nome da coluna."
                }],
              "text": "- O nome da coluna."
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Remove o formatador de valores de uma coluna da grade."
            }, {
              "name": "param",
              "text": "columnName - O nome da coluna."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "setFieldProp": {
        "complexType": {
          "signature": "(fieldName: string, propName: string, value: any) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "fieldName - O nome do campo."
                }],
              "text": "- O nome do campo."
            }, {
              "tags": [{
                  "name": "param",
                  "text": "propName - O nome da propriedade."
                }],
              "text": "- O nome da propriedade."
            }, {
              "tags": [{
                  "name": "param",
                  "text": "value - O valor da propriedade."
                }],
              "text": "- O valor da propriedade."
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Altera/adiciona uma propriedade nos metadados do campo."
            }, {
              "name": "param",
              "text": "fieldName - O nome do campo."
            }, {
              "name": "param",
              "text": "propName - O nome da propriedade."
            }, {
              "name": "param",
              "text": "value - O valor da propriedade."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "goToView": {
        "complexType": {
          "signature": "(view: VIEW_MODE) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "view - A vis\u00E3o para a qual navegar."
                }],
              "text": "- A vis\u00E3o para a qual navegar."
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "VIEW_MODE": {
              "location": "import",
              "path": "../../lib/utils/constants"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Usado para alternar a vis\u00E3o entre GRID e FORM externamente."
            }, {
              "name": "param",
              "text": "view - A vis\u00E3o para a qual navegar."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "setMetadata": {
        "complexType": {
          "signature": "(metadata: UnitMetadata) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "metadata - Os metadados a serem definidos."
                }],
              "text": "- Os metadados a serem definidos."
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "UnitMetadata": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Define os metadados do DataUnit."
            }, {
              "name": "param",
              "text": "metadata - Os metadados a serem definidos."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "setRecords": {
        "complexType": {
          "signature": "(records: Array<Record>) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "records - Os registros a serem definidos."
                }],
              "text": "- Os registros a serem definidos."
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "Array": {
              "location": "global"
            },
            "Record": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Define os registros do DataUnit."
            }, {
              "name": "param",
              "text": "records - Os registros a serem definidos."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "getRecords": {
        "complexType": {
          "signature": "() => Promise<Array<Record>>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            },
            "Record": {
              "location": "import",
              "path": "@sankhyalabs/core"
            },
            "Array": {
              "location": "global"
            }
          },
          "return": "Promise<Record[]>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Obt\u00E9m os registros do DataUnit."
            }, {
              "name": "returns",
              "text": "Uma promessa que resolve com a lista de registros."
            }]
        }
      },
      "openConfigurator": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Usado para abrir o configurador do CRUD."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "closeConfigurator": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Usado para fechar o configurador do CRUD."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "updateConfig": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "description",
              "text": "Atualiza a configura\u00E7\u00E3o do formul\u00E1rio."
            }, {
              "name": "returns",
              "text": undefined
            }]
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
  static get watchers() {
    return [{
        "propName": "resourceID",
        "methodName": "handleResourceIDChanged"
      }, {
        "propName": "entityName",
        "methodName": "onChangeEntityName"
      }, {
        "propName": "mode",
        "methodName": "onModeChange"
      }, {
        "propName": "dataState",
        "methodName": "observeDataState"
      }, {
        "propName": "formLegacyConfigName",
        "methodName": "observeFormLegacy"
      }, {
        "propName": "gridLegacyConfigName",
        "methodName": "observeGridLegacy"
      }];
  }
  static get listeners() {
    return [{
        "name": "actionClick",
        "method": "actionClickListener",
        "target": undefined,
        "capture": false,
        "passive": false
      }];
  }
}
var TASKBAR_ID;
(function (TASKBAR_ID) {
  TASKBAR_ID["FORM_REGULAR"] = "snkSimpleCrudTaskbar.form_regular";
  TASKBAR_ID["GRID_REGULAR"] = "snkSimpleCrudTaskbar.grid_regular";
  TASKBAR_ID["FORM_SELECTED"] = "snkSimpleCrudTaskbar.form_selected";
  TASKBAR_ID["GRID_SELECTED"] = "snkSimpleCrudTaskbar.grid_selected";
  TASKBAR_ID["FINISH_EDITION"] = "snkSimpleCrudTaskbar.finish_edition";
  TASKBAR_ID["MULTIPLE_EDITION"] = "snkSimpleCrudTaskbar.multiple_edition";
})(TASKBAR_ID || (TASKBAR_ID = {}));
