import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { Action, StringUtils, ElementIDUtils, ApplicationContext, KeyboardManager } from '@sankhyalabs/core';
import './DataFetcher.js';
import { P as PresentationMode, E as ExporterStrategy } from './ISave.js';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import './dataunit-fetcher.js';
import './filter-item-type.enum.js';
import './form-config-fetcher.js';
import { V as VIEW_MODE } from './constants.js';
import { A as AutorizationType } from './auth-fetcher.js';
import { S as ServicesNumberingConfig, d as defineCustomElement$c } from './snk-numbering-config2.js';
import { T as TaskbarElement, d as defineCustomElement$6 } from './snk-taskbar2.js';
import { S as SimpleTaskbarProcessor, D as DEFAULT_TASKBAR_BUTTONS, C as CustomTaskbarButton, b as buildNativeTaskbarManager, g as getTopTaskBarId, a as getHeaderTaskbarId } from './taskbarUtils.js';
import { v as validateFilters, d as defineCustomElement$n } from './snk-filter-modal2.js';
import { buildFieldSearch } from '@sankhyalabs/ezui/dist/collection/utils';
import { C as ContinuousInsertUtils } from './ContinuousInsertUtils.js';
import { d as defineCustomElement$L } from './config-header2.js';
import { d as defineCustomElement$K } from './configs-button2.js';
import { d as defineCustomElement$J } from './field-config2.js';
import { d as defineCustomElement$I } from './field-item2.js';
import { d as defineCustomElement$H } from './fields-layout2.js';
import { d as defineCustomElement$G } from './fields-selector2.js';
import { d as defineCustomElement$F } from './guides-configurator2.js';
import { d as defineCustomElement$E } from './snk-actions-button2.js';
import { d as defineCustomElement$D } from './snk-attach2.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$z } from './snk-default-filter2.js';
import { d as defineCustomElement$f, a as defineCustomElement$y } from './snk-detail-view2.js';
import { d as defineCustomElement$x } from './snk-entity-search2.js';
import { d as defineCustomElement$w } from './snk-exporter-email-sender2.js';
import { d as defineCustomElement$v } from './snk-expression-group2.js';
import { d as defineCustomElement$u } from './snk-expression-item2.js';
import { d as defineCustomElement$t } from './snk-filter-advanced-mode2.js';
import { d as defineCustomElement$s } from './snk-filter-assistent-mode2.js';
import { d as defineCustomElement$r } from './snk-filter-bar2.js';
import { d as defineCustomElement$q } from './snk-filter-detail2.js';
import { d as defineCustomElement$p } from './snk-filter-field-search2.js';
import { d as defineCustomElement$o } from './snk-filter-item2.js';
import { d as defineCustomElement$m } from './snk-filter-modal-item2.js';
import { d as defineCustomElement$l } from './snk-filter-param-config2.js';
import { d as defineCustomElement$k } from './snk-form-config2.js';
import { d as defineCustomElement$j } from './snk-form-summary2.js';
import { d as defineCustomElement$i } from './snk-form-view2.js';
import { d as defineCustomElement$h } from './snk-grid2.js';
import { d as defineCustomElement$g } from './snk-grid-config2.js';
import { d as defineCustomElement$e } from './snk-image-input2.js';
import { d as defineCustomElement$d } from './snk-layout-form-config2.js';
import { d as defineCustomElement$b } from './snk-personalized-filter2.js';
import { d as defineCustomElement$a } from './snk-select-box2.js';
import { d as defineCustomElement$9 } from './snk-simple-bar2.js';
import { d as defineCustomElement$8 } from './snk-simple-crud2.js';
import { d as defineCustomElement$7 } from './snk-simple-form-config2.js';
import { d as defineCustomElement$5 } from './snk-taskbar-skeleton2.js';
import { d as defineCustomElement$4 } from './snk-view-representation2.js';
import { d as defineCustomElement$3 } from './taskbar-actions-button2.js';
import { d as defineCustomElement$2 } from './taskbar-split-button2.js';

const snkCrudCss = ".sc-snk-crud-h{display:flex;flex-direction:column;height:100%;width:100%;overflow-y:auto;scrollbar-gutter:stable both-edges}snk-grid.sc-snk-crud{--snk-grid-padding:0 var(--space--6, 6px) var(--space--6, 6px) var(--space--6, 6px)}stack-item.sc-snk-crud.sc-snk-crud{display:grid;min-height:100%}.snk-crud__header.sc-snk-crud{margin-bottom:var(--space--10, 10px)}.snk-crud__grid-stack-item.sc-snk-crud{display:flex;flex-direction:column;height:100%;width:100%;padding:0 var(--space--2, 2px)}.snk-crud__header-top.sc-snk-crud{display:flex;justify-content:space-between;align-items:center;padding:var(--space--8, 8px);padding-top:var(--space--12, 12px)}.snk-crud__header-bottom.sc-snk-crud{display:flex;justify-content:space-between;align-items:center;padding:0 var(--space--8, 8px) 0 var(--space--6, 6px)}.snk-crud__header-bottom.sc-snk-crud>snk-taskbar.sc-snk-crud{padding-bottom:var(--space--8, 8px);margin-left:var(--space--12, 12px)}.snk-crud--hidden.sc-snk-crud{display:none !important}ez-record-navigation.sc-snk-crud,ez-grid-pagination.sc-snk-crud{margin-bottom:var(--space--8, 8px)}";

const SnkCrud$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.snkShowGuide = createEvent(this, "snkShowGuide", 7);
    this.actionClick = createEvent(this, "actionClick", 7);
    this.configuratorSave = createEvent(this, "configuratorSave", 7);
    this.configuratorCancel = createEvent(this, "configuratorCancel", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    this.viewModeChanged = createEvent(this, "viewModeChanged", 7);
    this.numberingConfigChanged = createEvent(this, "numberingConfigChanged", 7);
    this._viewHistory = [];
    this._customEditors = new Map();
    this._customRenders = new Map();
    this._taskbarProcessor = new SimpleTaskbarProcessor(DEFAULT_TASKBAR_BUTTONS);
    this._taskbarCustomProcessor = new SimpleTaskbarProcessor([]);
    this.dataUnitInterceptor = {
      interceptAction: async (action) => {
        switch (action.type) {
          case Action.DATA_SAVED:
            return this.interceptDataSaved(action);
          case Action.LOADING_DATA:
            return await this.interceptLoadData(action);
          default:
            return action;
        }
      },
    };
    this._dataUnit = undefined;
    this._dataState = undefined;
    this.attachmentRegisterKey = undefined;
    this._currentViewMode = VIEW_MODE.GRID;
    this._canEdit = undefined;
    this._resourceID = undefined;
    this.customContainerId = `SNK-CRUD-CUSTOM-CONTAINER-${StringUtils.generateUUID()}`;
    this.numberingConfig = undefined;
    this._filterMode = 'regular';
    this._enableContinuousInsert = false;
    this._headerVisible = true;
    this.enableLockManagerLoadingComp = false;
    this.enableLockManagerTaskbarClick = false;
    this.configName = undefined;
    this.filterBarTitle = undefined;
    this.selectionToastConfig = undefined;
    this.showActionButtons = true;
    this.actionsList = undefined;
    this.taskbarManager = undefined;
    this.recordsValidator = undefined;
    this.statusResolver = undefined;
    this.multipleSelection = true;
    this.presentationMode = PresentationMode.PRIMARY;
    this.messagesBuilder = undefined;
    this.useEnterLikeTab = false;
    this.gridLegacyConfigName = undefined;
    this.filterBarLegacyConfigName = undefined;
    this.formLegacyConfigName = undefined;
    this.disablePersonalizedFilter = undefined;
    this.autoLoad = undefined;
    this.autoFocus = true;
    this.enableGridInsert = false;
    this.domainMessagesBuilder = undefined;
    this.ignoreReadOnlyFormFields = undefined;
    this.setCustomFormTitle = undefined;
    this.strategyExporter = ExporterStrategy.SERVER_SIDE;
    this.layoutFormConfig = true;
    this.multipleEditionEnabled = true;
    this.paginationCounterMode = 'auto';
    this.customGuidesConfig = [];
    this.showEntitySearch = true;
    this.disableNumberingConfig = false;
  }
  handleActionClick(evt) {
    this.executeAction(evt.detail);
  }
  /**
   * Usado para alternar a visão entre GRID e FORM externamente.
   */
  async goToView(mode) {
    this.executeAction(mode);
  }
  /**
   * Usado para abrir o configurator do CRUD
   */
  async openConfigurator() {
    var _a;
    (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.open();
  }
  /**
   * Usado para fechar o configurator do CRUD
   */
  async closeConfigurator() {
    var _a;
    (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.close();
  }
  /**
   * Faz o recarregamento da filter-bar do crud, buscando o state no servidor.
   */
  async reloadFilterBar() {
    var _a;
    (_a = this._snkGrid) === null || _a === void 0 ? void 0 : _a.reloadFilterBar();
  }
  /**
   * Retorna o elemento da filter-bar da grade.
   */
  async getFilterBar() {
    return await this._snkGrid.getFilterBar();
  }
  /**
   * Registra um editor customizado para campos da grade e formulário.
   */
  async addCustomEditor(fieldName, customEditor) {
    if (this._guidesViewer && this._snkGrid) {
      this._guidesViewer.addCustomEditor(fieldName, customEditor);
      this._snkGrid.addCustomEditor(fieldName, customEditor);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, customEditor);
    this._customEditors = newCustomEditors;
  }
  /**
   * Registra um render customizado para colunas da grid.
   */
  async addGridCustomRender(fieldName, customRender) {
    if (this._snkGrid) {
      this._snkGrid.addGridCustomRender(fieldName, customRender);
      return;
    }
    const newCustomRenders = new Map(this._customRenders);
    newCustomRenders.set(fieldName, customRender);
    this._customRenders = newCustomRenders;
  }
  /**
   * Registra um formatador de valores para uma coluna da grid.
   */
  async addCustomValueFormatter(columnName, customFormatter) {
    this._snkGrid.addCustomValueFormatter(columnName, customFormatter);
  }
  /**
   * Remove o formatador de valores de uma coluna da grid.
   */
  async removeCustomValueFormatter(columnName) {
    this._snkGrid.removeCustomValueFormatter(columnName);
  }
  /**
   * Altera/adiciona uma propriedade nos metadados do campo.
   */
  async setFieldProp(fieldName, propName, value) {
    await this._guidesViewer.setFieldProp(fieldName, propName, value);
  }
  /**
   * Retorna a configuração de numeração atual.
   */
  async getNumberingConfig() {
    return this.numberingConfig;
  }
  /**
   * Atualiza a configuração de numeração.
   */
  async updateNumberingConfig(config) {
    this.numberingConfig = config;
    this.applyNumberingConfigToFields();
  }
  currentViewModeWatcher(currentView) {
    this._viewHistory = [...this._viewHistory.slice(-1), currentView];
  }
  async gridToForm(keepFormMode = false) {
    this._backToGrid = !keepFormMode && await this._viewStack.getSelectedIndex() === VIEW_MODE.GRID;
    this.setViewMode(VIEW_MODE.FORM);
  }
  async executeAction(act) {
    var _a;
    switch (act) {
      case TaskbarElement.GRID_MODE:
        return this.setViewMode(VIEW_MODE.GRID);
      case TaskbarElement.FORM_MODE:
      case TaskbarElement.UPDATE:
        return this.gridToForm(act !== TaskbarElement.UPDATE);
      case TaskbarElement.UPDATE_MULTIPLE:
        this._dataUnit.isMultipleEdition = true;
        return this.setViewMode(VIEW_MODE.FORM);
      case TaskbarElement.CONFIGURATOR:
        return this._snkConfigurator.open();
      case TaskbarElement.ATTACH:
        return this._snkAttach.open();
      case CustomTaskbarButton.FILTER:
        return (_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.showFilterModal();
      case CustomTaskbarButton.ENTITY_SEARCH:
        return this.openSearchPopover();
    }
  }
  setViewMode(viewMode) {
    this._viewStack.show(viewMode);
    this._currentViewMode = viewMode;
    if (viewMode === VIEW_MODE.GRID) {
      this._dataUnit.isMultipleEdition = false;
      this._snkGrid.setFocus();
    }
    else if (viewMode === VIEW_MODE.FORM) {
      this._guidesViewer.setFocus();
    }
    this.viewModeChanged.emit(viewMode);
  }
  openConfig(viewMode) {
    this._snkConfigurator.close();
    if (viewMode === VIEW_MODE.GRID) {
      this._snkGrid.showConfig();
    }
    else if (viewMode === VIEW_MODE.FORM) {
      this._guidesViewer.showFormConfig();
    }
  }
  addDataElementID() {
    const dataInfo = { dataUnit: this._dataUnit };
    ElementIDUtils.addIDInfo(this._element, null, dataInfo);
  }
  insertionModeHandler() {
    if (this.enableGridInsert)
      return;
    this.gridToForm();
  }
  cancelHandler() {
    if (this._backToGrid) {
      this.setViewMode(VIEW_MODE.GRID);
    }
  }
  async getAttachmentRegisterKey() {
    if (!this._snkDataUnit)
      return;
    const recordCriteria = await this._snkDataUnit.getSelectedRecordsIDsInfo();
    const joinedPrimaryKeys = recordCriteria.map(({ value }) => value).join('_');
    return joinedPrimaryKeys;
  }
  setCustomRenders() {
    if (!this._snkGrid) {
      return;
    }
    for (const [fieldName, customRender] of this._customRenders) {
      this._snkGrid.addGridCustomRender(fieldName, customRender);
      this._customRenders.delete(fieldName);
    }
  }
  setCustomEditors() {
    if (!this._snkGrid || !this._guidesViewer) {
      return;
    }
    for (const [fieldName, customEditor] of this._customEditors) {
      this._guidesViewer.addCustomEditor(fieldName, customEditor);
      this._snkGrid.addCustomEditor(fieldName, customEditor);
      this._customEditors.delete(fieldName);
    }
  }
  initializeTaskbarProcessor() {
    const nativeTaskbarManager = buildNativeTaskbarManager(this._currentViewMode, this.taskbarManager, this.messagesBuilder);
    const topTaskbarId = getTopTaskBarId(this._dataState, this.presentationMode);
    this._taskbarProcessor.process(topTaskbarId, nativeTaskbarManager, this._dataState, undefined, []);
    const headerTaskbarId = getHeaderTaskbarId(this._dataState, this.presentationMode);
    this._taskbarCustomProcessor.process(headerTaskbarId, this.taskbarManager, this._dataState, undefined, []);
  }
  componentWillRender() {
    this.initializeTaskbarProcessor();
  }
  componentDidRender() {
    this.setCustomRenders();
    this.setCustomEditors();
  }
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    let parent = this._element.parentElement;
    this._application
      .hasAccess(AutorizationType.UPDATE, this._resourceID)
      .then(canEdit => this._canEdit = canEdit);
    while (parent) {
      if (parent.tagName.toUpperCase() === "SNK-DATA-UNIT") {
        this._snkDataUnit = parent;
        this._snkDataUnit.addEventListener("insertionMode", () => this.insertionModeHandler());
        this._snkDataUnit.addEventListener("cancelEdition", () => this.cancelHandler());
        this._snkDataUnit.domainMessagesBuilder = this.domainMessagesBuilder;
        this._dataUnit = this._snkDataUnit.dataUnit;
        this._dataState = this._snkDataUnit.dataState;
        if (!this._dataUnit) {
          this._snkDataUnit.addEventListener("dataUnitReady", (evt) => {
            this._dataUnit = evt.detail;
            this.initDataUnit();
          });
        }
        else {
          this.initDataUnit();
        }
        this._snkDataUnit.addEventListener("dataStateChange", this.handleDataStateChange.bind(this));
        break;
      }
      parent = parent.parentElement;
    }
    if (!this.configName) {
      this.configName = this._application.configName;
    }
    this.initContinuousInsertUtils();
  }
  componentDidLoad() {
    this.initKeyboardManager();
  }
  disconnectedCallback() {
    var _a;
    this.removeShortcuts();
    (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.removeInterceptor(this.dataUnitInterceptor);
  }
  async handleDataStateChange(evt) {
    var _a;
    this._dataState = evt.detail;
    if (this._dataState.selectedRecord !== undefined) {
      this.attachmentRegisterKey = await this.getAttachmentRegisterKey();
    }
    const fieldsWithRmPrecision = await this._snkDataUnit.getFieldsWithRmPrecision();
    for (const field of fieldsWithRmPrecision || []) {
      if (!field) {
        continue;
      }
      const rmPrecision = (_a = this._dataState.rowMetadata) === null || _a === void 0 ? void 0 : _a.getProp('rm_precision', field);
      if (!rmPrecision && rmPrecision !== 0) {
        continue;
      }
      await this.setFieldProp(field, 'precision', rmPrecision);
      await this.setFieldProp(field, 'prettyPrecision', rmPrecision);
    }
  }
  async initKeyboardManager() {
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element });
    const dataUnit = this._dataUnit || await this._snkDataUnit.getDataUnit();
    async function saveDataUnitHandlingFocus() {
      const element = document.activeElement;
      const isDocumentBody = (element == document.body);
      if (!isDocumentBody)
        element.blur();
      await dataUnit.saveData();
      if (!isDocumentBody && element.setFocus != undefined) {
        element.setFocus();
        return;
      }
      if (!isDocumentBody)
        element.focus();
    }
    async function handleAddRecord() {
      if (!dataUnit.hasNewRecord()) {
        dataUnit.addRecord();
      }
    }
    if (this._keyboardManager) {
      this._keyboardManager
        .bind("F6", this.toggleView.bind(this), { description: this.getMessage("snkCrud.shortcuts.toggleView"), element: this._element })
        .bind("F7", saveDataUnitHandlingFocus.bind(this), { description: this.getMessage("snkCrud.shortcuts.saveData"), element: this._element })
        .bind("ctrl + \\", saveDataUnitHandlingFocus.bind(this), { description: this.getMessage("snkCrud.shortcuts.addRecord"), element: this._element })
        .bind("F8", handleAddRecord.bind(this), { description: this.getMessage("snkCrud.shortcuts.addRecord"), element: this._element })
        .bind("F9", dataUnit.removeSelectedRecords.bind(dataUnit), { description: this.getMessage("snkCrud.shortcuts.removeRecord"), element: this._element })
        .bind("ctrl + F9", dataUnit.removeSelectedRecords.bind(dataUnit), { description: this.getMessage("snkCrud.shortcuts.removeRecord"), element: this._element })
        .bind("F5", async () => {
        const currentView = await this._viewStack.getSelectedIndex();
        if (VIEW_MODE.GRID === currentView) {
          dataUnit.loadData();
        }
      }, { description: this.getMessage("snkCrud.shortcuts.refreshData"), element: this._element })
        .bind("Escape", () => {
        if (dataUnit.isDirty()) {
          dataUnit.cancelEdition();
        }
      }, {
        debounceTime: 1000,
        description: this.getMessage("snkCrud.shortcuts.cancelAction"), element: this._element
      });
    }
  }
  getMessage(key, params) {
    if (this.messagesBuilder)
      return this.messagesBuilder.getMessage(key, params);
  }
  async removeShortcuts() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  async toggleView() {
    const currentView = await this._viewStack.getSelectedIndex();
    this.setViewMode(VIEW_MODE.GRID === currentView ? VIEW_MODE.FORM : VIEW_MODE.GRID);
  }
  getLastRecordSaved(action) {
    var _a;
    if ((_a = action.payload) === null || _a === void 0 ? void 0 : _a.records.length) {
      return action.payload.records[action.payload.records.length - 1];
    }
    return null;
  }
  async saveNumberingConfig() {
    const payload = {
      entityName: this._snkDataUnit.entityName,
      isAutoNum: this.numberingConfig.isAutoNumbering,
      numInicial: this.numberingConfig.initialNumber
    };
    await this._servicesNumberingConfig.saveConfig(payload);
  }
  updateNumberingConfigAfterInsert(action) {
    var _a, _b;
    if (!((_a = action.payload) === null || _a === void 0 ? void 0 : _a.changes.length) || this.disableNumberingConfig || !((_b = this.numberingConfig) === null || _b === void 0 ? void 0 : _b.isAutoNumbering) || !this._fieldAutoNum) {
      return action;
    }
    if (!action.payload.changes.some((change) => change.operation === 'INSERT' || change.operation === 'COPY')) {
      return action;
    }
    const lastRecord = this.getLastRecordSaved(action);
    if (lastRecord && lastRecord.hasOwnProperty(this._fieldAutoNum)) {
      const currentNumber = Number(lastRecord[this._fieldAutoNum]);
      this.numberingConfig.initialNumber = currentNumber;
      this.saveNumberingConfig();
    }
    else {
      this.numberingConfig.initialNumber = this.numberingConfig.initialNumber + 1;
    }
    this.numberingConfigChanged.emit(this.numberingConfig);
    return action;
  }
  interceptDataSaved(action) {
    this.updateNumberingConfigAfterInsert(action);
    return action;
  }
  async interceptLoadData(action) {
    var _a;
    const hasInvalidFilters = !validateFilters((_a = this._snkFilterBar) === null || _a === void 0 ? void 0 : _a.filterConfig);
    if (hasInvalidFilters) {
      const errorTitle = this.messagesBuilder.getMessage("snkGrid.requiredFiltersNotFilled.title", {});
      const errorMessage = this.messagesBuilder.getMessage("snkGrid.requiredFiltersNotFilled.message", {});
      await this._application.error(errorTitle, errorMessage);
      return;
    }
    return action;
  }
  onDataUnitReady() {
    var _a;
    (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.addInterceptor(this.dataUnitInterceptor);
    this.loadNumberingConfig();
  }
  async initDataUnit() {
    this.addDataElementID();
    if (!this.messagesBuilder) {
      this.messagesBuilder = this._snkDataUnit.messagesBuilder;
    }
    if (this._resourceID == undefined) {
      //Tenta pegar o resourceID do snkDataUnit;
      this._resourceID = this._snkDataUnit.resourceID;
      if (this._resourceID == undefined) {
        this._resourceID = await this._application.getResourceID();
      }
    }
    this.onDataUnitReady();
  }
  initContinuousInsertUtils() {
    this._continuousInsertUtils = new ContinuousInsertUtils(this._application, this._resourceID, this.configName);
    if (this.enableGridInsert) {
      this._continuousInsertUtils.getConfig().then(value => this._enableContinuousInsert = value);
    }
  }
  async loadNumberingConfig() {
    if (this.numberingConfig || !this._snkDataUnit || !this._snkDataUnit.entityName || this.disableNumberingConfig) {
      return;
    }
    if (!this._servicesNumberingConfig) {
      this._servicesNumberingConfig = new ServicesNumberingConfig(this._application, this._resourceID);
    }
    try {
      this.numberingConfig = await this._servicesNumberingConfig.getConfig(this._snkDataUnit.entityName);
      this.getFieldAutoNum();
      this.applyNumberingConfigToFields();
    }
    catch (error) {
      console.error("Error loading numbering config in snk-crud:", error);
      this.numberingConfig = {
        isAutoNumbering: false,
        initialNumber: null
      };
    }
  }
  getFieldAutoNum() {
    if (this._fieldAutoNum) {
      return;
    }
    const fieldAutoNum = this._dataUnit.metadata.fields.find((field) => { var _a; return ((_a = field.properties) === null || _a === void 0 ? void 0 : _a["isAutoNumField"]) === "true"; });
    this._fieldAutoNum = (fieldAutoNum === null || fieldAutoNum === void 0 ? void 0 : fieldAutoNum.name) || null;
  }
  async applyNumberingConfigToFields() {
    if (!this.numberingConfig || !this._snkDataUnit || !this._fieldAutoNum) {
      return;
    }
    const field = this._dataUnit.getField(this._fieldAutoNum);
    field.readOnly = this.numberingConfig.isAutoNumbering;
    field.required = !this.numberingConfig.isAutoNumbering;
  }
  handleConfiguratorEvent(evt, type) {
    evt.stopImmediatePropagation();
    if (type === 'SAVE') {
      this._guidesViewer.reloadGuides();
      this.configuratorSave.emit();
      return;
    }
    this.configuratorCancel.emit();
  }
  renderCustomGuideSlots() {
    if (!this.customGuidesConfig)
      return;
    return this.customGuidesConfig.map(g => h("slot", { name: g.id }));
  }
  getColumnSearch(item) {
    if (this._columnSearch != undefined) {
      return this._columnSearch;
    }
    this._columnSearch = buildFieldSearch(item, ({ argument }) => new Promise(accept => {
      this._snkGrid.filterColumns(argument).then((columns) => {
        accept(columns
          .filter(column => !column.hidden)
          .map(column => ({ label: column.label, value: column.name })));
      });
    }), (option) => {
      if (option != undefined) {
        this._snkGrid.locateColumn(option.value);
      }
    });
    return this._columnSearch;
  }
  buildTaskbarCustomActionsList() {
    return [this.buildSearchColumnTaskbarAction()];
  }
  buildSearchColumnTaskbarAction() {
    return {
      value: StringUtils.generateUUID(),
      label: this.messagesBuilder.getMessage('snkGrid.findColumn', {}),
      disableCloseOnSelect: true,
      eagerInitialize: true,
      itemBuilder: (_, item) => this.getColumnSearch(item),
    };
  }
  isGridInsertActive() {
    return this.enableGridInsert && this._dataUnit.hasNewRecord();
  }
  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 = getTopTaskBarId(this._dataState, this.presentationMode);
      return hardList.concat(this.taskbarManager.getMoreOptions(taskbarID, this.configName, this._dataState, this.actionsList));
    }
    return hardList.concat(this.actionsList);
  }
  async openSearchPopover() {
    if (!this._popoverSearchEntity) {
      return;
    }
    const buttonElement = this._element.querySelector(`[data-taskbar-element="${CustomTaskbarButton.ENTITY_SEARCH}"]`);
    await this._popoverSearchEntity.showUnder(buttonElement);
  }
  handleLoadedSearch(evt) {
    if (evt.detail.length === 1) {
      this._dataUnit.selectFirst();
      this.gridToForm(true);
    }
  }
  renderDynamicSearch() {
    var _a;
    if (!this.showEntitySearch)
      return;
    return (h("snk-entity-search", { ref: (ref) => this._popoverSearchEntity = ref, dataUnit: this._dataUnit, entityName: (_a = this._snkDataUnit) === null || _a === void 0 ? void 0 : _a.entityName, messagesBuilder: this.messagesBuilder, onLoaded: (evt) => this.handleLoadedSearch(evt) }));
  }
  handleFilterConfigUpdated(filterConfig) {
    if (!filterConfig.length) {
      return;
    }
    if (filterConfig.length === 1 && filterConfig[0].id === 'PERSONALIZED_FILTER_GROUP') {
      this._filterMode = filterConfig[0].groupedItems.length > 0 ? 'regular' : 'button';
      return;
    }
  }
  render() {
    if (this._resourceID == undefined) {
      return;
    }
    this._snkDataUnit.ignoreSaveMessage = (this._currentViewMode === VIEW_MODE.GRID && !this.enableGridInsert);
    return (h(Host, null, h("header", { class: { 'snk-crud--hidden': !this._headerVisible, 'snk-crud__header': true } }, h("div", { class: "snk-crud__header-top" }, h("snk-taskbar", { "data-element-id": "grid_top", key: "snkGridTopTaskbar", configName: this.configName, dataUnit: this._dataUnit, messagesBuilder: this.messagesBuilder, buttons: this._taskbarProcessor.buttons, disabledButtons: this._taskbarProcessor.disabledButtons, customButtons: this._taskbarProcessor.customButtons, resourceID: this._resourceID, primaryButton: "INSERT", overflowStrategy: "hiddenItems", alignRigth: true, actionsList: this.getActionsList(), customActionsList: this.buildTaskbarCustomActionsList(), sizeButtons: 'medium' })), h("snk-filter-bar", { ref: (ref) => this._snkFilterBar = ref, title: this.filterBarTitle, dataUnit: this._dataUnit, "data-element-id": "gridFilter", class: "snk-grid__filter-bar ez-align--top", configName: this.configName, messagesBuilder: this.messagesBuilder, resourceID: this._resourceID, onConfigUpdated: evt => this.handleFilterConfigUpdated(evt.detail), disablePersonalizedFilter: this.disablePersonalizedFilter, filterBarLegacyConfigName: this.filterBarLegacyConfigName, autoLoad: this.autoLoad, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, mode: this._filterMode, hideFilterButton: true, sizeChips: 'default' })), h("ez-view-stack", { ref: (ref) => this._viewStack = ref, "data-element-id": "crud" }, h("stack-item", { class: 'snk-crud__grid-stack-item' }, h("snk-grid", { ref: (ref) => this._snkGrid = ref, class: 'ez-flex ez-flex--column ez-size-height--full ez-size-width--full', filterBarTitle: this.filterBarTitle, "data-element-id": "crud_grid", configName: this.configName, onGridDoubleClick: () => this.gridToForm(true), taskbarManager: this.taskbarManager, onActionClick: evt => this.executeAction(evt.detail), messagesBuilder: this.messagesBuilder, actionsList: this.actionsList, statusResolver: this.statusResolver, multipleSelection: this.multipleSelection, presentationMode: this.presentationMode, recordsValidator: this.recordsValidator, selectionToastConfig: this.selectionToastConfig, useEnterLikeTab: this.useEnterLikeTab, canEdit: this._canEdit, resourceID: this._resourceID, disablePersonalizedFilter: this.disablePersonalizedFilter, gridLegacyConfigName: this.gridLegacyConfigName, filterBarLegacyConfigName: this.filterBarLegacyConfigName, autoLoad: this.autoLoad, autoFocus: this.autoFocus, enableGridInsert: this.enableGridInsert, enableLockManagerTaskbarClick: this.enableLockManagerTaskbarClick, enableLockManagerLoadingComp: this.enableLockManagerLoadingComp, strategyExporter: this.strategyExporter, multipleEditionEnabled: this.multipleEditionEnabled, paginationCounterMode: this.paginationCounterMode, hideHeader: true, hideGridTaskbar: true }, h("slot", { name: "GRID_TASKBAR_CUSTOM_ELEMENTS" }), h("slot", { name: "GRID_HEADER_CUSTOM_ELEMENTS" }), h("slot", { name: "SnkGridHeader" }), h("slot", { name: "SnkGridFooter" }), h("slot", { name: "SnkGridTaskBar" }))), h("stack-item", null, h("snk-guides-viewer", { ref: ref => this._guidesViewer = ref, customGuidesConfig: this.customGuidesConfig, entityPath: this._snkDataUnit.entityName, messagesBuilder: this.messagesBuilder, onExit: () => this.setViewMode(VIEW_MODE.GRID), dataState: this._dataState, dataUnit: this._dataUnit, actionsList: this.actionsList, taskbarManager: this.taskbarManager, configName: this.configName, onActionClick: evt => this.executeAction(evt.detail), presentationMode: this.presentationMode, "data-element-id": "crud_form", canEdit: this._canEdit, recordsValidator: this.recordsValidator, resourceID: this._resourceID, detailTaskbarCustomContainerId: this.customContainerId, formLegacyConfigName: this.formLegacyConfigName, enableGridInsert: this.enableGridInsert, getCustomTitle: this.setCustomFormTitle, ignoreReadOnlyFormFields: this.ignoreReadOnlyFormFields, onFormConfigVisibilityChanged: evt => this._headerVisible = !evt.detail }, h("slot", { name: "GUIDES_VIEWER_TASKBAR_CUSTOM_ELEMENTS" }), this.renderCustomGuideSlots(), h("slot", { name: "SnkFormTaskBar" })))), h("snk-attach", { ref: (ref) => this._snkAttach = ref, registerKey: this.attachmentRegisterKey, messagesBuilder: this.messagesBuilder, entityName: this._snkDataUnit.entityName }), h("snk-configurator", { ref: (ref) => this._snkConfigurator = ref, entityName: this._snkDataUnit.entityName, viewMode: this._currentViewMode, messagesBuilder: this.messagesBuilder, onConfigSelected: (evt) => this.setViewMode(evt.detail), onOpenConfig: (evt) => this.openConfig(evt.detail), showActionButtons: this.showActionButtons, onSave: evt => this.handleConfiguratorEvent(evt, 'SAVE'), onCancel: evt => this.handleConfiguratorEvent(evt, 'CANCEL'), resourceID: this._resourceID, customContainerId: this.customContainerId, layoutFormConfig: this.layoutFormConfig }), this.renderDynamicSearch(), h("div", { id: `${this.customContainerId}` }, h("slot", { name: "SnkConfigContainerSlot" }), h("slot", { name: "DETAIL_GRID_HEADER_CUSTOM_ELEMENTS" }), h("slot", { name: "DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS" }), h("slot", { name: "DETAIL_TASKBAR_CUSTOM_ELEMENTS" }))));
  }
  get _element() { return this; }
  static get watchers() { return {
    "_currentViewMode": ["currentViewModeWatcher"]
  }; }
  static get style() { return snkCrudCss; }
}, [6, "snk-crud", {
    "enableLockManagerLoadingComp": [4, "enable-lock-manager-loading-comp"],
    "enableLockManagerTaskbarClick": [4, "enable-lock-manager-taskbar-click"],
    "configName": [1025, "config-name"],
    "filterBarTitle": [1, "filter-bar-title"],
    "selectionToastConfig": [16],
    "showActionButtons": [4, "show-action-buttons"],
    "actionsList": [16],
    "taskbarManager": [16],
    "recordsValidator": [16],
    "statusResolver": [16],
    "multipleSelection": [4, "multiple-selection"],
    "presentationMode": [1, "presentation-mode"],
    "messagesBuilder": [1040],
    "useEnterLikeTab": [4, "use-enter-like-tab"],
    "gridLegacyConfigName": [1, "grid-legacy-config-name"],
    "filterBarLegacyConfigName": [1, "filter-bar-legacy-config-name"],
    "formLegacyConfigName": [1, "form-legacy-config-name"],
    "disablePersonalizedFilter": [4, "disable-personalized-filter"],
    "autoLoad": [4, "auto-load"],
    "autoFocus": [4, "auto-focus"],
    "enableGridInsert": [4, "enable-grid-insert"],
    "domainMessagesBuilder": [1, "domain-messages-builder"],
    "ignoreReadOnlyFormFields": [4, "ignore-read-only-form-fields"],
    "setCustomFormTitle": [16],
    "strategyExporter": [1025, "strategy-exporter"],
    "layoutFormConfig": [4, "layout-form-config"],
    "multipleEditionEnabled": [4, "multiple-edition-enabled"],
    "paginationCounterMode": [1, "pagination-counter-mode"],
    "customGuidesConfig": [16],
    "showEntitySearch": [4, "show-entity-search"],
    "disableNumberingConfig": [4, "disable-numbering-config"],
    "_dataUnit": [32],
    "_dataState": [32],
    "attachmentRegisterKey": [32],
    "_currentViewMode": [32],
    "_canEdit": [32],
    "_resourceID": [32],
    "customContainerId": [32],
    "numberingConfig": [32],
    "_filterMode": [32],
    "_enableContinuousInsert": [32],
    "_headerVisible": [32],
    "goToView": [64],
    "openConfigurator": [64],
    "closeConfigurator": [64],
    "reloadFilterBar": [64],
    "getFilterBar": [64],
    "addCustomEditor": [64],
    "addGridCustomRender": [64],
    "addCustomValueFormatter": [64],
    "removeCustomValueFormatter": [64],
    "setFieldProp": [64],
    "getNumberingConfig": [64],
    "updateNumberingConfig": [64]
  }, [[0, "actionClick", "handleActionClick"]]]);
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-crud", "config-header", "configs-button", "field-config", "field-item", "fields-layout", "fields-selector", "guides-configurator", "snk-actions-button", "snk-attach", "snk-configurator", "snk-data-exporter", "snk-data-unit", "snk-default-filter", "snk-detail-view", "snk-entity-search", "snk-exporter-email-sender", "snk-expression-group", "snk-expression-item", "snk-filter-advanced-mode", "snk-filter-assistent-mode", "snk-filter-bar", "snk-filter-detail", "snk-filter-field-search", "snk-filter-item", "snk-filter-modal", "snk-filter-modal-item", "snk-filter-param-config", "snk-form-config", "snk-form-summary", "snk-form-view", "snk-grid", "snk-grid-config", "snk-guides-viewer", "snk-image-input", "snk-layout-form-config", "snk-numbering-config", "snk-personalized-filter", "snk-select-box", "snk-simple-bar", "snk-simple-crud", "snk-simple-form-config", "snk-taskbar", "snk-taskbar-skeleton", "snk-view-representation", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-crud":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkCrud$1);
      }
      break;
    case "config-header":
      if (!customElements.get(tagName)) {
        defineCustomElement$L();
      }
      break;
    case "configs-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$K();
      }
      break;
    case "field-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$J();
      }
      break;
    case "field-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$I();
      }
      break;
    case "fields-layout":
      if (!customElements.get(tagName)) {
        defineCustomElement$H();
      }
      break;
    case "fields-selector":
      if (!customElements.get(tagName)) {
        defineCustomElement$G();
      }
      break;
    case "guides-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$F();
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$E();
      }
      break;
    case "snk-attach":
      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-default-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$z();
      }
      break;
    case "snk-detail-view":
      if (!customElements.get(tagName)) {
        defineCustomElement$y();
      }
      break;
    case "snk-entity-search":
      if (!customElements.get(tagName)) {
        defineCustomElement$x();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$w();
      }
      break;
    case "snk-expression-group":
      if (!customElements.get(tagName)) {
        defineCustomElement$v();
      }
      break;
    case "snk-expression-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$u();
      }
      break;
    case "snk-filter-advanced-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$t();
      }
      break;
    case "snk-filter-assistent-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$s();
      }
      break;
    case "snk-filter-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$r();
      }
      break;
    case "snk-filter-detail":
      if (!customElements.get(tagName)) {
        defineCustomElement$q();
      }
      break;
    case "snk-filter-field-search":
      if (!customElements.get(tagName)) {
        defineCustomElement$p();
      }
      break;
    case "snk-filter-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$o();
      }
      break;
    case "snk-filter-modal":
      if (!customElements.get(tagName)) {
        defineCustomElement$n();
      }
      break;
    case "snk-filter-modal-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$m();
      }
      break;
    case "snk-filter-param-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$l();
      }
      break;
    case "snk-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$k();
      }
      break;
    case "snk-form-summary":
      if (!customElements.get(tagName)) {
        defineCustomElement$j();
      }
      break;
    case "snk-form-view":
      if (!customElements.get(tagName)) {
        defineCustomElement$i();
      }
      break;
    case "snk-grid":
      if (!customElements.get(tagName)) {
        defineCustomElement$h();
      }
      break;
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$g();
      }
      break;
    case "snk-guides-viewer":
      if (!customElements.get(tagName)) {
        defineCustomElement$f();
      }
      break;
    case "snk-image-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$e();
      }
      break;
    case "snk-layout-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-numbering-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-personalized-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-simple-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-simple-crud":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-simple-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-taskbar":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-taskbar-skeleton":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "snk-view-representation":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "taskbar-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "taskbar-split-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
  } });
}

const SnkCrud = SnkCrud$1;
const defineCustomElement = defineCustomElement$1;

export { SnkCrud, defineCustomElement };
