'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-17105557.js');
const core = require('@sankhyalabs/core');
const taskbarElements = require('./taskbar-elements-f3ecbf5c.js');
require('./DataFetcher-21f8c2dc.js');
require('./ISave-f926fe9e.js');
const index$1 = require('./index-e3e39724.js');
require('@sankhyalabs/ezui/dist/collection/utils/constants');
require('@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata');
require('./dataunit-fetcher-6c85a04d.js');
require('./filter-item-type.enum-a7ffdaa6.js');
require('./form-config-fetcher-fef79845.js');
const constants = require('./constants-6d82e405.js');
const authFetcher = require('./auth-fetcher-61e18ad2.js');
require('./index-22a8223a.js');
require('./PrintUtils-bcaeb82f.js');
require('@sankhyalabs/ezui/dist/collection/components/ez-grid/utils');
require('@sankhyalabs/core/dist/utils/SortingUtils');
require('./ResourceIDUtils-5ff86aa7.js');

const snkCrudCss = ".sc-snk-crud-h{display:flex;flex-direction:column;height:100%;width:100%}";

const SnkCrud = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.actionClick = index.createEvent(this, "actionClick", 7);
    this.configuratorSave = index.createEvent(this, "configuratorSave", 7);
    this.configuratorCancel = index.createEvent(this, "configuratorCancel", 7);
    this.formItemsReady = index.createEvent(this, "formItemsReady", 7);
    this.viewModeChanged = index.createEvent(this, "viewModeChanged", 7);
    this._viewHistory = [];
    this._customEditors = new Map();
    this._customRenders = new Map();
    this._dataUnit = undefined;
    this._dataState = undefined;
    this.attachmentRegisterKey = undefined;
    this._currentViewMode = constants.VIEW_MODE.GRID;
    this._canEdit = undefined;
    this._resourceID = undefined;
    this.enableLockManagerLoadingComp = false;
    this.enableLockManagerTaskbarClick = false;
    this.configName = undefined;
    this.filterBarTitle = undefined;
    this.selectionToastConfig = undefined;
    this.showActionButtons = false;
    this.actionsList = undefined;
    this.taskbarManager = undefined;
    this.recordsValidator = undefined;
    this.statusResolver = undefined;
    this.multipleSelection = true;
    this.presentationMode = index$1.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 = index$1.ExporterStrategy.SERVER_SIDE;
    this.layoutFormConfig = true;
    this.multipleEditionEnabled = true;
    this.paginationCounterMode = 'auto';
    this.customContainerId = `SNK-CRUD-CUSTOM-CONTAINER-${core.StringUtils.generateUUID()}`;
  }
  /**
   * 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);
  }
  currentViewModeWatcher(currentView) {
    this._viewHistory = [...this._viewHistory.slice(-1), currentView];
  }
  async gridToForm(keepFormMode = false) {
    this._backToGrid = !keepFormMode && await this._viewStack.getSelectedIndex() === constants.VIEW_MODE.GRID;
    this.setViewMode(constants.VIEW_MODE.FORM);
  }
  async executeAction(act) {
    switch (act) {
      case taskbarElements.TaskbarElement.GRID_MODE:
        return this.setViewMode(constants.VIEW_MODE.GRID);
      case taskbarElements.TaskbarElement.FORM_MODE:
      case taskbarElements.TaskbarElement.UPDATE:
        return this.gridToForm(act !== taskbarElements.TaskbarElement.UPDATE);
      case taskbarElements.TaskbarElement.UPDATE_MULTIPLE:
        this._dataUnit.isMultipleEdition = true;
        return this.setViewMode(constants.VIEW_MODE.FORM);
      case taskbarElements.TaskbarElement.CONFIGURATOR:
        return this._snkConfigurator.open();
      case taskbarElements.TaskbarElement.ATTACH:
        return this.setViewMode(constants.VIEW_MODE.ATTACHMENT);
    }
  }
  backView() {
    const lastView = this._viewHistory.at(-2) || constants.VIEW_MODE.GRID;
    this.setViewMode(lastView);
  }
  setViewMode(viewMode) {
    this._viewStack.show(viewMode);
    this._currentViewMode = viewMode;
    if (viewMode === constants.VIEW_MODE.GRID) {
      this._dataUnit.isMultipleEdition = false;
      this._snkGrid.setFocus();
    }
    else if (viewMode === constants.VIEW_MODE.FORM) {
      this._guidesViewer.setFocus();
    }
    this.viewModeChanged.emit(viewMode);
  }
  openConfig(viewMode) {
    this._snkConfigurator.close();
    if (viewMode === constants.VIEW_MODE.GRID) {
      this._snkGrid.showConfig();
    }
    else if (viewMode === constants.VIEW_MODE.FORM) {
      this._guidesViewer.showFormConfig();
    }
  }
  addDataElementID() {
    const dataInfo = { dataUnit: this._dataUnit };
    core.ElementIDUtils.addIDInfo(this._element, null, dataInfo);
  }
  insertionModeHandler() {
    if (this.enableGridInsert)
      return;
    this.gridToForm();
  }
  cancelHandler() {
    if (this._backToGrid) {
      this.setViewMode(constants.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);
    }
  }
  componentDidRender() {
    this.setCustomRenders();
    this.setCustomEditors();
  }
  componentWillLoad() {
    this._application = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
    let parent = this._element.parentElement;
    this._application
      .hasAccess(authFetcher.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;
    }
  }
  componentDidLoad() {
    this.initKeyboardManager();
  }
  disconnectedCallback() {
    this.removeShortcuts();
  }
  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 core.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 (constants.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(constants.VIEW_MODE.GRID === currentView ? constants.VIEW_MODE.FORM : constants.VIEW_MODE.GRID);
  }
  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();
      }
    }
  }
  handleConfiguratorEvent(evt, type) {
    evt.stopImmediatePropagation();
    if (type === 'SAVE') {
      this.configuratorSave.emit();
      return;
    }
    this.configuratorCancel.emit();
  }
  render() {
    if (this._resourceID == undefined) {
      return;
    }
    this._snkDataUnit.ignoreSaveMessage = (this._currentViewMode === constants.VIEW_MODE.GRID && !this.enableGridInsert);
    return (index.h(index.Host, null, index.h("ez-view-stack", { ref: (ref) => this._viewStack = ref, "data-element-id": "crud" }, index.h("stack-item", { class: 'ez-flex ez-flex--column ez-size-height--full ez-size-width--full ez-padding--medium' }, index.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 }, index.h("slot", { name: "GRID_TASKBAR_CUSTOM_ELEMENTS" }), index.h("slot", { name: "GRID_HEADER_CUSTOM_ELEMENTS" }), index.h("slot", { name: "SnkGridHeader" }), index.h("slot", { name: "SnkGridFooter" }), index.h("slot", { name: "SnkGridTaskBar" }))), index.h("stack-item", null, index.h("snk-guides-viewer", { ref: ref => this._guidesViewer = ref, entityPath: this._snkDataUnit.entityName, messagesBuilder: this.messagesBuilder, onExit: () => this.setViewMode(constants.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 }, index.h("slot", { name: "GUIDES_VIEWER_TASKBAR_CUSTOM_ELEMENTS" }), index.h("slot", { name: "SnkFormTaskBar" }))), index.h("stack-item", { tabIndex: "0" }, index.h("snk-attach", { registerKey: this.attachmentRegisterKey, messagesBuilder: this.messagesBuilder, entityName: this._snkDataUnit.entityName, onBack: this.backView.bind(this) })), index.h("snk-configurator", { ref: (ref) => this._snkConfigurator = ref, 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 })), index.h("div", { id: `${this.customContainerId}` }, index.h("slot", { name: "SnkConfigContainerSlot" }), index.h("slot", { name: "DETAIL_GRID_HEADER_CUSTOM_ELEMENTS" }), index.h("slot", { name: "DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS" }), index.h("slot", { name: "DETAIL_TASKBAR_CUSTOM_ELEMENTS" }))));
  }
  get _element() { return index.getElement(this); }
  static get watchers() { return {
    "_currentViewMode": ["currentViewModeWatcher"]
  }; }
};
SnkCrud.style = snkCrudCss;

exports.snk_crud = SnkCrud;
