import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { StringUtils, ApplicationContext, ObjectUtils, Action, DataType, UserInterface, KeyboardManager, ElementIDUtils } from '@sankhyalabs/core';
import { CSSVarsUtils, buildFieldSearch } from '@sankhyalabs/ezui/dist/collection/utils';
import { V as VIEW_MODE, S as SIMPLE_CRUD_MODE } from './constants.js';
import { T as TaskbarElement, d as defineCustomElement$4 } from './snk-taskbar2.js';
import './DataFetcher.js';
import { P as PresentationMode } from './ISave.js';
import { S as SnkMultiSelectionListDataSource, T as TaskbarProcessor, R as RmPrecisionCustomValueFormatter, b as ContinuousInsertUtils, a as CrudUtils, c as ClientSideExporterProvider } from './ContinuousInsertUtils.js';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import { I as InMemoryLoader } from './dataunit-fetcher.js';
import './filter-item-type.enum.js';
import { F as FormConfigFetcher } from './form-config-fetcher.js';
import { C as ConfigStorage } from './ConfigStorage.js';
import { S as SnkFormConfigManager } from './SnkFormConfigManager.js';
import { s as store } from './index2.js';
import { d as defineCustomElement$d } from './snk-actions-button2.js';
import { d as defineCustomElement$c } from './snk-configurator2.js';
import { d as defineCustomElement$b } from './snk-data-exporter2.js';
import { d as defineCustomElement$a } from './snk-data-unit2.js';
import { d as defineCustomElement$9 } from './snk-exporter-email-sender2.js';
import { d as defineCustomElement$8 } from './snk-grid-config2.js';
import { d as defineCustomElement$7 } from './snk-layout-form-config2.js';
import { d as defineCustomElement$6 } from './snk-select-box2.js';
import { d as defineCustomElement$5 } from './snk-simple-form-config2.js';
import { d as defineCustomElement$3 } from './snk-view-representation2.js';
import { d as defineCustomElement$2 } from './taskbar-actions-button2.js';
import { d as defineCustomElement$1 } from './taskbar-split-button2.js';

const REGULAR_DEFAULT_BTNS = ["INSERT", "REFRESH", "PREVIOUS", "NEXT", "DIVIDER", "MORE_OPTIONS"];
const REGULAR_SELECTED_BTNS = ["INSERT", "REFRESH", "PREVIOUS", "NEXT", "DIVIDER", "CLONE", "REMOVE", "DIVIDER", "MORE_OPTIONS"];

const snkSimpleCrudCss = ".sc-snk-simple-crud-h{display:flex;height:100%;width:100%;--snk-simple-crud-grid--min-height:300px}.simple-crud__container.sc-snk-simple-crud{display:grid;grid-template-rows:auto 1fr;height:100%;width:100%}.simple-crud__container-section.sc-snk-simple-crud{flex-wrap:unset;flex-direction:column}.simple-crud__form--hidden.sc-snk-simple-crud{display:none}ez-grid.sc-snk-simple-crud{--ez-grid__container--shadow:none;--ez-grid__container--shadow--outline:none;--ez-grid--min-height:var(--snk-simple-crud-grid--min-height)}ez-form.sc-snk-simple-crud{min-height:300px}";

const SnkSimpleCrud = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.dataStateChange = createEvent(this, "dataStateChange", 3);
    this.dataUnitReady = createEvent(this, "dataUnitReady", 3);
    this.actionClick = createEvent(this, "actionClick", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    this.configuratorSave = createEvent(this, "configuratorSave", 7);
    this.configuratorCancel = createEvent(this, "configuratorCancel", 7);
    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 === Action.EDITION_CANCELED || action.type === Action.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() }))));
  }
  get _element() { return this; }
  static get watchers() { return {
    "resourceID": ["handleResourceIDChanged"],
    "entityName": ["onChangeEntityName"],
    "mode": ["onModeChange"],
    "dataState": ["observeDataState"],
    "formLegacyConfigName": ["observeFormLegacy"],
    "gridLegacyConfigName": ["observeGridLegacy"]
  }; }
  static get style() { return snkSimpleCrudCss; }
}, [6, "snk-simple-crud", {
    "enableLockManagerLoadingComp": [4, "enable-lock-manager-loading-comp"],
    "enableLockManagerTaskbarClick": [4, "enable-lock-manager-taskbar-click"],
    "dataState": [1040],
    "dataUnit": [16],
    "entityName": [1, "entity-name"],
    "mode": [2],
    "gridConfig": [1040],
    "formConfig": [1040],
    "enableContinuousInsert": [1028, "enable-continuous-insert"],
    "multipleSelection": [4, "multiple-selection"],
    "useCancelConfirm": [4, "use-cancel-confirm"],
    "pageSize": [2, "page-size"],
    "resourceID": [1, "resource-i-d"],
    "enableGridInsert": [4, "enable-grid-insert"],
    "paginationCounterMode": [1, "pagination-counter-mode"],
    "taskbarManager": [16],
    "messagesBuilder": [1040],
    "useEnterLikeTab": [4, "use-enter-like-tab"],
    "actionsList": [16],
    "configName": [1025, "config-name"],
    "showConfiguratorButtons": [4, "show-configurator-buttons"],
    "gridLegacyConfigName": [1, "grid-legacy-config-name"],
    "formLegacyConfigName": [1, "form-legacy-config-name"],
    "ignoreReadOnlyFormFields": [4, "ignore-read-only-form-fields"],
    "autoFocus": [4, "auto-focus"],
    "domainMessagesBuilder": [1, "domain-messages-builder"],
    "multipleEditionEnabled": [4, "multiple-edition-enabled"],
    "layoutFormConfig": [4, "layout-form-config"],
    "disableGridEdition": [4, "disable-grid-edition"],
    "autoLoad": [4, "auto-load"],
    "outlineMode": [4, "outline-mode"],
    "_container": [32],
    "_showPopUpGridConfig": [32],
    "_currentViewMode": [32],
    "_config": [32],
    "_fieldToGetFocus": [32],
    "_customContainerId": [32],
    "_formFields": [32],
    "_fieldsProps": [32],
    "addCustomEditor": [64],
    "addGridCustomRender": [64],
    "addCustomValueFormatter": [64],
    "removeCustomValueFormatter": [64],
    "setFieldProp": [64],
    "goToView": [64],
    "setMetadata": [64],
    "setRecords": [64],
    "getRecords": [64],
    "openConfigurator": [64],
    "closeConfigurator": [64],
    "updateConfig": [64]
  }, [[0, "actionClick", "actionClickListener"]]]);
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 = {}));
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-simple-crud", "snk-actions-button", "snk-configurator", "snk-data-exporter", "snk-data-unit", "snk-exporter-email-sender", "snk-grid-config", "snk-layout-form-config", "snk-select-box", "snk-simple-form-config", "snk-taskbar", "snk-view-representation", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-simple-crud":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkSimpleCrud);
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-data-exporter":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-data-unit":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-layout-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-simple-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "snk-taskbar":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "snk-view-representation":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "taskbar-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
    case "taskbar-split-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}

export { SnkSimpleCrud as S, defineCustomElement as d };
