import { r as registerInstance, e as createEvent, h, F as Fragment, g as getElement } from './index-04f73a26.js';
import { ObjectUtils, StringUtils, Action, KeyboardManager, ElementIDUtils } from '@sankhyalabs/core';
import { buildFieldSearch, SHORTCUT_SEARCH_FIELD } from '@sankhyalabs/ezui/dist/collection/utils';
import { buildFormMetadata, FormMetadata } from '@sankhyalabs/ezui/dist/collection/utils/form';
import { a as TAB_NAMES, V as VIEW_MODE } from './constants-7b422de0.js';
import { C as ConfigStorage } from './ConfigStorage-32841866.js';
import { F as FormConfigFetcher } from './form-config-fetcher-1c81efc4.js';
import { T as TaskbarElement } from './taskbar-elements-63651ca7.js';

class SnkFormConfigManager {
  constructor(configName, resourceID, onConfigChange, dataUnit) {
    this._resourceID = resourceID;
    this._configName = configName;
    this._onConfigChange = onConfigChange;
    this._dataUnit = dataUnit;
  }
  addFormLegacyConfig(legacyConfigName) {
    if (this._configName) {
      ConfigStorage.addFormLegacyConfig(this._configName, legacyConfigName);
    }
  }
  async loadConfig() {
    return new Promise(resolve => {
      ConfigStorage.loadFormConfig(this._configName, this._resourceID)
        .then((config) => {
        config = this.buildFormMetadataUITabs(config);
        this.setConfig(config);
        resolve(config);
      })
        .catch((error) => {
        console.warn(error);
      });
    });
  }
  getEmptyConfig() {
    return this.buildFormMetadataUITabs({ fields: [], emptyConfig: true }, true);
  }
  saveConfig(config) {
    const configToSave = ObjectUtils.copy(config);
    return new Promise(accept => {
      ConfigStorage.saveFormConfig(config, this._configName, this._resourceID)
        .then((response) => {
        this.setConfig(Object.assign(Object.assign({}, configToSave), response));
        accept(Object.assign(Object.assign({}, configToSave), response));
      });
    });
  }
  saveCardState(cardId, cardConfig, propertyChanged) {
    return new Promise(resolve => {
      var _a;
      const cardsState = ((_a = this._config) === null || _a === void 0 ? void 0 : _a.cardsState) || new Map;
      const currentConfig = cardsState.get(cardId);
      cardsState.set(cardId, propertyChanged === "fixed" ?
        this.updateFixSequence(Object.assign(Object.assign({}, currentConfig), { fixed: cardConfig.fixed }), cardsState)
        : Object.assign(Object.assign({}, currentConfig), { [propertyChanged]: cardConfig[propertyChanged] }));
      ConfigStorage.saveCardState(cardsState, this._configName, this._resourceID)
        .then(savedCardConfig => {
        this._config = Object.assign(Object.assign({}, this._config), { cardsState });
        resolve(savedCardConfig);
      });
    });
  }
  updateFixSequence(updatingCardConfig, cardsState) {
    let maxSequence = -1;
    Array.from(cardsState.values()).forEach(cardConfig => {
      if (!cardConfig.fixed) {
        delete updatingCardConfig.fixSequence;
      }
      if (cardConfig.fixSequence != undefined) {
        maxSequence = Math.max(maxSequence, cardConfig.fixSequence);
      }
    });
    if (updatingCardConfig.fixed) {
      updatingCardConfig.fixSequence = maxSequence + 1;
    }
    else {
      delete updatingCardConfig.fixSequence;
    }
    return updatingCardConfig;
  }
  hasConfig(config) {
    var _a;
    const currentConfig = config !== null && config !== void 0 ? config : this._config;
    if (currentConfig && ((_a = currentConfig.fields) === null || _a === void 0 ? void 0 : _a.length)) {
      return true;
    }
    return false;
  }
  getFieldsList(descriptionFilter, forceEmptyConfig = false) {
    var _a, _b;
    const fields = (_a = this._config) === null || _a === void 0 ? void 0 : _a.fields;
    const hasConfig = this.hasConfig();
    if (hasConfig && !forceEmptyConfig) {
      return fields.map(({ label, name, readOnly, visible, required, tab, group }) => {
        var _a;
        if (label == undefined) {
          const currentField = (_a = this._dataUnit) === null || _a === void 0 ? void 0 : _a.getField(name);
          if (!currentField)
            return;
          return Object.assign(Object.assign({}, currentField), { name: name !== null && name !== void 0 ? name : currentField.name, readOnly: readOnly !== null && readOnly !== void 0 ? readOnly : currentField.readOnly, visible: visible !== null && visible !== void 0 ? visible : currentField.visible, required: required !== null && required !== void 0 ? required : currentField.required, tab: tab, group: group });
        }
        return { name, label, readOnly, visible, required, tab, group };
      })
        .filter(field => this.isFieldVisible(field, descriptionFilter));
    }
    if (!this._dataUnit || !((_b = this._dataUnit.metadata) === null || _b === void 0 ? void 0 : _b.fields)) {
      return [];
    }
    const filteredFields = this._dataUnit.metadata.fields
      .filter(field => this.isFieldVisible(field, descriptionFilter))
      .map(({ label, name, readOnly, visible, required, properties }) => ({ label, name, readOnly, visible, required, tab: properties === null || properties === void 0 ? void 0 : properties.UITabName }));
    return filteredFields;
  }
  isFieldVisible(field, descriptionFilter) {
    if (field === undefined || field.visible === false) {
      return false;
    }
    if (descriptionFilter == undefined) {
      return true;
    }
    const normalizedText = StringUtils.replaceAccentuatedCharsLower((field.label || field.name).toLocaleLowerCase());
    const normalizedFilter = StringUtils.replaceAccentuatedCharsLower(descriptionFilter.toLocaleLowerCase());
    return normalizedText.includes(normalizedFilter);
  }
  getFormConfig(dataUnit, ignoreReadOnlyFormFields, forceEmptyConfig = false) {
    let fields = this.getFieldsList(undefined, forceEmptyConfig);
    if (ignoreReadOnlyFormFields) {
      fields = fields.filter(field => {
        if (dataUnit) {
          const def = dataUnit.getField(field.name);
          if (def && def.readOnly) {
            return false;
          }
        }
        return !field.readOnly;
      });
    }
    return Object.assign(Object.assign({}, this._config), { fields });
  }
  setConfig(config) {
    this.isLoaded = true;
    const { cardsState, summary, defaultVars } = this._config || {};
    this._config = Object.assign({}, config);
    if (cardsState) {
      this._config.cardsState = cardsState;
    }
    if (summary) {
      this._config.summary = summary;
    }
    if (defaultVars) {
      this._config.defaultVars = defaultVars;
    }
    if (this._onConfigChange) {
      this._onConfigChange(Object.assign({}, this._config));
    }
  }
  getConfig(dataUnit, ignoreReadOnlyFormFields) {
    return this.getFormConfig(dataUnit, ignoreReadOnlyFormFields);
  }
  getFormConfigFetcher() {
    if (this._formConfigFetcher == undefined) {
      this._formConfigFetcher = new FormConfigFetcher();
    }
    return this._formConfigFetcher;
  }
  async fetchUserAvailableConfigs() {
    if (this._configName != undefined) {
      //FIXME: Precisamos preparar o backend para retornar as configurações disponíveis para details;
      return Promise.resolve(undefined);
    }
    return this.getFormConfigFetcher().fetchUserAvailableConfigs(this._configName, this._resourceID);
  }
  async fetchLegacyConfig() {
    return this.getFormConfigFetcher().fetchLegacyConfig(this._configName, this._resourceID);
  }
  async fetchDefaultConfig() {
    return this.getFormConfigFetcher().fetchDefaultConfig(this._configName, this._resourceID);
  }
  parseObjectList(object) {
    if (!object) {
      return [];
    }
    return Array.isArray(object) ? object : [object];
  }
  buildFormMetadataUITabs(config, forceEmptyConfig = false) {
    var _a, _b, _c;
    const hasConfig = this.hasConfig(config);
    if (!forceEmptyConfig && (!this._dataUnit || hasConfig)) {
      return config;
    }
    config = this.getFormConfig(this._dataUnit, false, true);
    config.tabs = this.parseObjectList(config.tabs);
    config.emptyConfig = false;
    config.defaultConfiguration = true;
    const fields = (_b = (_a = this._dataUnit.metadata) === null || _a === void 0 ? void 0 : _a.fields) !== null && _b !== void 0 ? _b : [];
    for (const currentField of fields) {
      const field = config.fields.find(field => field.name === currentField.name);
      const uiTabName = (_c = currentField.properties) === null || _c === void 0 ? void 0 : _c.UITabName;
      if (!uiTabName || uiTabName === TAB_NAMES.main) {
        continue;
      }
      const haveTab = config.tabs.some((tab) => tab.label === uiTabName);
      if (!haveTab) {
        config.tabs.push({
          label: uiTabName,
          name: uiTabName,
          order: 0,
          visible: true,
        });
      }
      if (field) {
        field.tab = uiTabName;
      }
    }
    return config;
  }
}

const snkDynaformGuidesViewCss = ".sc-snk-dynaform-guides-view-h{--snk-guides-viewer--space-large:var(--space--large, 24px);--snk-guides-viewer--space-small:var(--space--2xs, 8px);--snk-guides-viewer__header--min-height:68px;--snk-guides-viewer__header--z-index:var(--more-visible, 2);--snk-guides-viewer__header--background-color:var(--background--body, #fafcff);display:block;height:100%;min-width:0;overflow-x:hidden}snk-dynaform-form-view.sc-snk-dynaform-guides-view{width:100%}.snk-guides-viewer.sc-snk-dynaform-guides-view{position:relative;display:flex;flex-direction:column;height:100%;overflow:hidden;padding:0px}.snk-guides-viewer__detail-container.sc-snk-dynaform-guides-view{display:flex;row-gap:24px;flex-direction:column;flex:1.2;min-height:0;overflow:hidden;margin-bottom:var(--space--12, 12px)}.snk-guides-viewer__container.sc-snk-dynaform-guides-view>snk-dynaform-form-view.sc-snk-dynaform-guides-view{flex:1;min-height:0;overflow-y:auto}.snk-guides-viewer__detail-container.sc-snk-dynaform-guides-view>snk-dynaform-form-view.sc-snk-dynaform-guides-view,.snk-guides-viewer__detail-container.sc-snk-dynaform-guides-view>snk-dynaform-detail-view.sc-snk-dynaform-guides-view{flex:1;min-height:0;overflow-y:auto}.snk-guides-viewer__header.sc-snk-dynaform-guides-view{position:sticky;align-items:center;top:0;z-index:var(--snk-guides-viewer__header--z-index);background-color:var(--snk-guides-viewer__header--background-color);padding:var(--snk-guides-viewer--space-small)}.snk-guides-viewer__header-breadcrumb.sc-snk-dynaform-guides-view{width:25%;display:flex}.snk-guides-viewer__header-taskbar.sc-snk-dynaform-guides-view{width:75%}.snk-guides-viewer__container.sc-snk-dynaform-guides-view{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden}.snk-guides-viewer__tabselector.sc-snk-dynaform-guides-view{width:100%;min-width:0;box-sizing:border-box;padding:0 var(--space--12, 12px);flex-shrink:0}";

const SnkDynaformGuidesViewer = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.snkMasterFormConfigChange = createEvent(this, "snkMasterFormConfigChange", 7);
    this.formConfigVisibilityChanged = createEvent(this, "formConfigVisibilityChanged", 7);
    this.exit = createEvent(this, "exit", 7);
    this.actionClick = createEvent(this, "actionClick", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    this.dataUnit = undefined;
    this.dataState = undefined;
    this.configName = undefined;
    this.entityPath = undefined;
    this.actionsList = undefined;
    this.recordsValidator = undefined;
    this.masterFormConfig = undefined;
    this.selectedGuide = undefined;
    this.taskbarManager = undefined;
    this.messagesBuilder = undefined;
    this.canEdit = true;
    this.presentationMode = undefined;
    this.resourceID = undefined;
    this.detailTaskbarCustomContainerId = undefined;
    this.formLegacyConfigName = undefined;
    this.enableGridInsert = false;
    this.ignoreReadOnlyFormFields = undefined;
    this.getCustomTitle = undefined;
    this.customGuidesConfig = [];
    this._guides = [];
    this._formEditorConfigManager = undefined;
    this._formEditorDataUnit = undefined;
    this._fieldToGetFocus = undefined;
    this._customEditors = {};
    this._customRenders = {};
    this._fieldsProps = {};
    this._mainForm = undefined;
    this._mainFormName = undefined;
    this._errorTabs = new Set();
    this._hasToCreateFieldSearch = true;
  }
  observeDataUnit() {
    this.loadGuides(true);
  }
  async observeFormConfigManager(value) {
    var _a, _b;
    const showFormConfig = !!value;
    await ((_a = this._viewStack) === null || _a === void 0 ? void 0 : _a.show(showFormConfig ?
      GUIDES_VIEWER_VIEW_MODE.CONFIG :
      GUIDES_VIEWER_VIEW_MODE.GUIDES));
    (_b = this.formConfigVisibilityChanged) === null || _b === void 0 ? void 0 : _b.emit(showFormConfig);
  }
  observeDataState(newValue, oldValue) {
    var _a, _b, _c, _d, _e, _f;
    const newRecordsIds = (_b = (_a = newValue === null || newValue === void 0 ? void 0 : newValue.selectionInfo) === null || _a === void 0 ? void 0 : _a.recordIds) !== null && _b !== void 0 ? _b : (_c = newValue === null || newValue === void 0 ? void 0 : newValue.selectedRecord) === null || _c === void 0 ? void 0 : _c['__record__id__'];
    const oldRecordsIds = (_e = (_d = oldValue === null || oldValue === void 0 ? void 0 : oldValue.selectionInfo) === null || _d === void 0 ? void 0 : _d.recordIds) !== null && _e !== void 0 ? _e : (_f = oldValue === null || oldValue === void 0 ? void 0 : oldValue.selectedRecord) === null || _f === void 0 ? void 0 : _f['__record__id__'];
    if (!ObjectUtils.equals(newRecordsIds, oldRecordsIds)) {
      this.loadGuides((oldValue === null || oldValue === void 0 ? void 0 : oldValue.insertionMode) != (newValue === null || newValue === void 0 ? void 0 : newValue.insertionMode));
    }
  }
  observeMasterFormConfig() {
    var _a;
    this.loadGuides(this.noGuideSelected());
    (_a = this.snkMasterFormConfigChange) === null || _a === void 0 ? void 0 : _a.emit(this.masterFormConfig);
  }
  /**
  * Abre o configurador do formulário
  * @param detail - Define se a configuração que está sendo carregada é
  * referente a um form detail.
  */
  async showFormConfig(detail = false) {
    var _a, _b;
    const masterConfig = !detail || this._currentDetail == undefined;
    this._formEditorConfigManager = masterConfig ? this._configManager : (_a = this._currentDetail) === null || _a === void 0 ? void 0 : _a.formConfigManager;
    this._formEditorDataUnit = masterConfig ? this.dataUnit : (_b = this._currentDetail) === null || _b === void 0 ? void 0 : _b.dataUnit;
  }
  /**
   * Registra um editor customizado para campos da grade e formulário
   */
  async addCustomEditor(fieldName, customEditor) {
    this._customEditors = Object.assign(Object.assign({}, this._customEditors), { [fieldName]: customEditor });
  }
  /**
   * Registra um render customizado para colunas da grid.
   */
  async addGridCustomRender(fieldName, customRender) {
    this._customRenders = Object.assign(Object.assign({}, this._customRenders), { [fieldName]: customRender });
  }
  ;
  /**
   * Altera/adiciona uma propriedade nos metadados do campo.
   */
  async setFieldProp(fieldName, propName, value) {
    const newFieldsProps = {
      [fieldName]: Object.assign(Object.assign({}, this._fieldsProps[fieldName]), { [propName]: value })
    };
    this._fieldsProps = Object.assign(Object.assign({}, this._fieldsProps), newFieldsProps);
  }
  /**
   * Atribui o foco para o componente.
   */
  async setFocus() {
    var _a;
    (_a = this._container) === null || _a === void 0 ? void 0 : _a.focus({ preventScroll: true });
  }
  /**
   * Recarrega os guias baseada nos metadados atuais.
   */
  async reloadGuides() {
    this.loadGuides(false);
  }
  exitViewer() {
    var _a, _b;
    if (!this.enableGridInsert && ((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.isDirty())) {
      this.dataUnit.cancelEdition({ after: () => { var _a; return (_a = this.exit) === null || _a === void 0 ? void 0 : _a.emit(); } });
    }
    else {
      (_b = this.exit) === null || _b === void 0 ? void 0 : _b.emit();
    }
  }
  onActionClick(evt) {
    var _a;
    if (evt.detail === TaskbarElement.CONFIGURATOR) {
      if (evt.target.dataset.taskbarOwner != "master") {
        (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.open();
        evt.stopImmediatePropagation();
        evt.stopPropagation();
      }
    }
  }
  onContentCardChanged(evt) {
    if (!this._configManager || !this.dataUnit) {
      return;
    }
    SnkDynaformGuidesViewer.updateContentCard(evt.detail.formName, evt.detail.cardConfig, evt.detail.propertyChanged, this._configManager)
      .then(() => { var _a; return this.masterFormConfig = (_a = this._configManager) === null || _a === void 0 ? void 0 : _a.getConfig(this.dataUnit); });
  }
  /**
   * Conforme mecanismo de mensagens, é possível customizar as mensagens dos blocos de construção
   * através de um pequeno modulo na estrutura da aplicação:
   * - Criar um arquivo no seguinte caminho: /messages/appmessages.msg.js.
   * Para conhecer os detalhes do módulo, vide o arquivo neste projeto "/src/lib/message/resources/snk-crud.msg.ts"
   */
  getMessage(key) {
    var _a, _b, _c, _d, _e, _f;
    if ((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.isMultipleEdition) {
      const selectedRecords = (_c = (_b = this.dataUnit.getSelectionInfo()) === null || _b === void 0 ? void 0 : _b.records) !== null && _c !== void 0 ? _c : [];
      return (_d = this.messagesBuilder) === null || _d === void 0 ? void 0 : _d.getMessage("snkCrud.multipleEdition.editing", { COUNT: selectedRecords.length });
    }
    return (_e = this.messagesBuilder) === null || _e === void 0 ? void 0 : _e.getMessage(key, (_f = this.dataUnit) === null || _f === void 0 ? void 0 : _f.getSelectedRecord());
  }
  loadGuides(changeSelection) {
    var _a;
    if (!this.dataUnit || !this._configManager) {
      return;
    }
    if (!this._configManager.isLoaded) {
      return;
    }
    this._masterFormMetadata = buildFormMetadata(this.masterFormConfig, this.dataUnit, true, this.customGuidesConfig);
    const allSheets = (_a = this._masterFormMetadata) === null || _a === void 0 ? void 0 : _a.getAllSheets();
    if (!allSheets) {
      return;
    }
    const currentRecord = this.dataUnit.getSelectedRecord();
    const disableDetails = this.hasToDisableDetails(currentRecord);
    const guides = [];
    let mainFormName;
    const listSheetsValues = Array.from(allSheets.values());
    listSheetsValues.forEach((sheet) => {
      if (mainFormName == undefined && !this.isDetail(sheet === null || sheet === void 0 ? void 0 : sheet.name) && !sheet.isCustom) {
        mainFormName = sheet === null || sheet === void 0 ? void 0 : sheet.name;
        return;
      }
      const item = { id: sheet === null || sheet === void 0 ? void 0 : sheet.name, label: sheet === null || sheet === void 0 ? void 0 : sheet.label };
      if (this.isDetail(sheet === null || sheet === void 0 ? void 0 : sheet.name) && disableDetails) {
        item.tooltip = this.getMessage("snkCrud.detail.tooltip.needSingleSelection");
        item.disabled = true;
      }
      if (sheet.isCustom && sheet.ctxProps) {
        Object.entries(sheet.ctxProps).forEach(([key, value]) => {
          if (value !== undefined) {
            item[key] = value;
          }
        });
      }
      if (!item.props) {
        item.props = {};
      }
      item.props.isAdditional = sheet.name.includes("AD_");
      item.props.isCustom = !!sheet.isCustom;
      guides.push(item);
    });
    this._mainFormName = mainFormName;
    this._guides = guides;
    if (changeSelection) {
      this.selectedGuide = this._guides && this._guides.length > 0 ? this._guides[0] : undefined;
    }
  }
  hasToDisableDetails(currentRecord) {
    return !currentRecord
      || !this.dataUnit
      || this.dataUnit.isNewRecord(currentRecord.__record__id__)
      || this.dataUnit.isMultipleEdition;
  }
  isDetail(formId) {
    return FormMetadata.getDetailName(formId) != undefined;
  }
  buildTabItems() {
    return this._guides.map((guide, index) => ({
      tabKey: guide.id,
      label: guide.label,
      index,
      disabled: guide.disabled,
      rightIcon: this._errorTabs.has(guide.id) ? 'alert-circle-inverted' : undefined,
      leftIcon: this.getTabLeftIcon(guide),
    }));
  }
  getTabLeftIcon(guide) {
    var _a, _b;
    if (guide.icon) {
      return guide.icon;
    }
    if ((_a = guide.props) === null || _a === void 0 ? void 0 : _a.isCustom) {
      return 'puzzle-piece';
    }
    if ((_b = guide.props) === null || _b === void 0 ? void 0 : _b.isAdditional) {
      return 'puzzle-piece';
    }
    return undefined;
  }
  isCustomGuide(guideId) {
    var _a;
    if (!guideId) {
      return false;
    }
    return !!((_a = this.customGuidesConfig) === null || _a === void 0 ? void 0 : _a.some(g => g.id === guideId));
  }
  onTabChange(tab) {
    const targetGuide = this._guides.find(g => g.id === tab.tabKey);
    if (!targetGuide || targetGuide.disabled) {
      return;
    }
    this.selectedGuide = targetGuide;
  }
  static updateContentCard(formName, cardConfig, propertyChanged, configManager) {
    return configManager.saveCardState(formName, cardConfig, propertyChanged);
  }
  static buildMainForm(params) {
    if (params.formMetadata == undefined || params.mainFormName == undefined) {
      return undefined;
    }
    const mainSheet = params.formMetadata.getSheet(params.mainFormName);
    if (mainSheet == undefined) {
      return undefined;
    }
    return (h("snk-dynaform-form-view", { ref: (ref) => { var _a; return (_a = params.onMainFormRef) === null || _a === void 0 ? void 0 : _a.call(params, ref); }, label: mainSheet.label, name: params.mainFormName, fields: mainSheet.fields, formMetadata: params.formMetadata, dataUnit: params.dataUnit, recordsValidator: params.recordsValidator, fieldToFocus: params.fieldToFocus, key: params.mainFormName, onSnkRequestClearFieldToFocus: _ => { var _a; return (_a = params.onRequestClearFieldToFocus) === null || _a === void 0 ? void 0 : _a.call(params); }, customEditors: params.propsCustomEditor, fieldsProps: params.fieldsProps, entityPath: params.entityPath, fieldSearch: params.fieldSearch }));
  }
  static buildFixedForms(params) {
    var _a;
    const cardsState = (_a = params.formConfig) === null || _a === void 0 ? void 0 : _a.cardsState;
    if (cardsState == undefined || params.formMetadata == undefined) {
      return undefined;
    }
    const fixedEntries = Array.from(cardsState.entries())
      .filter(([formName, cardConfig]) => (cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.fixed) && formName != params.selectedForm && formName != params.mainFormName)
      .sort(([, cardConfigA], [, cardConfigB]) => {
      const indexA = (cardConfigA === null || cardConfigA === void 0 ? void 0 : cardConfigA.fixSequence) || 0;
      const indexB = (cardConfigB === null || cardConfigB === void 0 ? void 0 : cardConfigB.fixSequence) || 0;
      return indexA - indexB;
    });
    if (fixedEntries.length === 0) {
      return undefined;
    }
    return (h(Fragment, null, fixedEntries.map(([formName]) => {
      const sheet = params.formMetadata.getSheet(formName);
      if (sheet == undefined) {
        return undefined;
      }
      return h("snk-dynaform-form-view", { label: sheet.label, name: formName, fields: sheet.fields, formMetadata: params.formMetadata, dataUnit: params.dataUnit, recordsValidator: params.recordsValidator, fieldToFocus: params.fieldToFocus, key: formName, onSnkRequestClearFieldToFocus: _ => { var _a; return (_a = params.onRequestClearFieldToFocus) === null || _a === void 0 ? void 0 : _a.call(params); }, customEditors: params.propsCustomEditor, fieldsProps: params.fieldsProps, entityPath: params.entityPath });
    })));
  }
  getContent() {
    var _a;
    if (!this.selectedGuide) {
      return undefined;
    }
    const guideId = this.selectedGuide.id;
    if (this.isCustomGuide(guideId)) {
      return h("slot", { name: guideId });
    }
    const childEntityName = FormMetadata.getDetailName(guideId);
    if (childEntityName) {
      return (h("snk-dynaform-detail-view", { ref: (ref) => {
          if (ref)
            this._currentDetail = ref;
        }, dataUnitName: `${this.entityPath}/${childEntityName}`, entityName: childEntityName, label: this.selectedGuide.label, key: `detail_${guideId}`, canEdit: this.canEdit, resourceID: this.resourceID, taskbarCustomContainerId: this.detailTaskbarCustomContainerId, customEditors: this._customEditors, customRenders: this._customRenders, presentationMode: this.presentationMode, messagesBuilder: this.messagesBuilder }));
    }
    if (guideId === this._mainFormName) {
      return undefined;
    }
    const sheet = (_a = this._masterFormMetadata) === null || _a === void 0 ? void 0 : _a.getSheet(guideId);
    if (!sheet) {
      return undefined;
    }
    return (h("snk-dynaform-form-view", { name: guideId, label: sheet.label, fields: sheet.fields, dataUnit: this.dataUnit, formMetadata: this._masterFormMetadata, recordsValidator: this.recordsValidator, fieldToFocus: this._fieldToGetFocus, key: guideId, onSnkRequestClearFieldToFocus: _ => this.clearFieldToFocusHandler(), customEditors: this._customEditors, fieldsProps: this._fieldsProps, fieldSearch: this._fieldSearch, entityPath: this.entityPath }));
  }
  clearFieldToFocusHandler() {
    this._fieldToGetFocus = undefined;
  }
  getConfigViewMode() {
    return VIEW_MODE.GRID;
  }
  changeConfigViewMode(mode) {
    var _a, _b;
    if (this._currentDetail) {
      (_b = (_a = this._currentDetail).changeViewMode) === null || _b === void 0 ? void 0 : _b.call(_a, mode);
    }
  }
  openConfig(mode) {
    var _a, _b, _c, _d;
    (_b = (_a = this._snkConfigurator) === null || _a === void 0 ? void 0 : _a.close) === null || _b === void 0 ? void 0 : _b.call(_a);
    if (this._currentDetail) {
      if (mode === VIEW_MODE.FORM) {
        this.showFormConfig(true);
      }
      else {
        (_d = (_c = this._currentDetail).configGrid) === null || _d === void 0 ? void 0 : _d.call(_c);
      }
    }
  }
  noGuideSelected() {
    var _a;
    return this.selectedGuide === undefined || '__main' === ((_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.id);
  }
  addFormLegacyConfigName() {
    var _a;
    if (this.formLegacyConfigName) {
      (_a = this._configManager) === null || _a === void 0 ? void 0 : _a.addFormLegacyConfig(this.formLegacyConfigName);
    }
  }
  setMasterFormConfig(config) {
    this.masterFormConfig = config;
  }
  componentWillLoad() {
    var _a;
    if (this.resourceID == undefined) {
      throw new Error((_a = this.getMessage("snkCrud.errors.resourceIDNotProvided")) !== null && _a !== void 0 ? _a : "");
    }
    this._configManager = new SnkFormConfigManager(this.configName, this.resourceID, this.setMasterFormConfig.bind(this), this.dataUnit);
    this.addFormLegacyConfigName();
    this._configManager.loadConfig();
  }
  async dataUnitActionHandler(action) {
    var _a, _b;
    switch (action.type) {
      case Action.EDITION_CANCELED:
      case Action.DATA_SAVED:
        if ((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.isMultipleEdition) {
          this.exitViewer();
          if (this.dataUnit) {
            this.dataUnit.isMultipleEdition = false;
          }
        }
        break;
      case Action.FIELD_INVALIDATED:
        const guideName = this.getGuideName((_b = action.payload) === null || _b === void 0 ? void 0 : _b.fieldName);
        if (guideName) {
          this._errorTabs = new Set([...this._errorTabs, guideName]);
        }
        break;
      case Action.METADATA_LOADED:
      case Action.MULTIPLE_EDITION_CHANGED:
        this.loadGuides(this.noGuideSelected());
        break;
    }
  }
  getGuideName(fieldName) {
    var _a, _b;
    const sheets = (_a = this._masterFormMetadata) === null || _a === void 0 ? void 0 : _a.getAllSheets();
    if (!sheets) {
      return "";
    }
    for (const sheet of sheets) {
      const formFields = (_b = sheet[1]) === null || _b === void 0 ? void 0 : _b.fields;
      if (!formFields)
        continue;
      for (const field of formFields) {
        if (field.name === fieldName) {
          return sheet[0];
        }
      }
    }
    return "";
  }
  getTitle() {
    var _a, _b, _c;
    return (_c = (_b = (_a = this.getCustomTitle) === null || _a === void 0 ? void 0 : _a.call(this)) !== null && _b !== void 0 ? _b : this.getMessage("snkCrud.title")) !== null && _c !== void 0 ? _c : "";
  }
  getTitleTooltip() {
    var _a;
    if (!((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.isMultipleEdition))
      return undefined;
    return this.buildRecordIdsArray();
  }
  buildRecordIdsArray() {
    var _a, _b, _c;
    const selectedRecords = (_c = (_b = (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getSelectionInfo()) === null || _b === void 0 ? void 0 : _b.records) !== null && _c !== void 0 ? _c : [];
    if (selectedRecords.length === 0) {
      return "[]";
    }
    const labels = selectedRecords.map(record => { var _a; return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage("snkCrud.title", record); });
    return `[${labels.join(", ")}]`;
  }
  getFieldsSearch() {
    var _a;
    if (this._fieldSearch == undefined || this._hasToCreateFieldSearch) {
      this._hasToCreateFieldSearch = false;
      const item = {
        label: (_a = this.getMessage("snkSimpleCrud.findFields")) !== null && _a !== void 0 ? _a : "Busca de campos",
        value: "findFields",
      };
      this._fieldSearch = buildFieldSearch(item, ({ argument }) => this.fieldsOptionLoader(argument), (option) => this.onSelectField(option));
    }
    return this._fieldSearch;
  }
  fieldsOptionLoader(argument) {
    var _a, _b;
    return Promise.resolve((_b = (_a = this._configManager) === null || _a === void 0 ? void 0 : _a.getFieldsList(argument).map(field => ({ value: field.name, label: field.label }))) !== null && _b !== void 0 ? _b : []);
  }
  onSelectField(option) {
    var _a, _b, _c;
    if (option == undefined) {
      return;
    }
    this._fieldToGetFocus = option.value;
    const fieldGuideName = this.getGuideName(option.value);
    if (!fieldGuideName) {
      return;
    }
    if (fieldGuideName === this._mainFormName) {
      (_b = (_a = this._mainForm) === null || _a === void 0 ? void 0 : _a.showUp) === null || _b === void 0 ? void 0 : _b.call(_a);
      return;
    }
    if (fieldGuideName !== ((_c = this.selectedGuide) === null || _c === void 0 ? void 0 : _c.id)) {
      const targetGuide = this._guides.find(g => g.id === fieldGuideName);
      if (targetGuide && !targetGuide.disabled) {
        this.selectedGuide = targetGuide;
      }
    }
  }
  componentDidLoad() {
    var _a;
    (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.subscribe(this.dataUnitActionHandler.bind(this));
    this.initKeyboardManager();
    this.getFieldsSearch();
  }
  disconnectedCallback() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  async initKeyboardManager() {
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element });
    if (this._keyboardManager) {
      this._keyboardManager.bind(SHORTCUT_SEARCH_FIELD, async () => {
        var _a, _b;
        if (!this._mainForm)
          return;
        await ((_b = (_a = this._mainForm).showSearchField) === null || _b === void 0 ? void 0 : _b.call(_a));
      }, { description: this.getMessage("snkSimpleCrud.findFields"), element: this._element });
    }
  }
  render() {
    var _a, _b, _c;
    if (this._formEditorConfigManager != undefined) {
      return (h("snk-dynaform-form-config", { ref: (ref) => {
          if (ref)
            this._container = ref;
        }, tabindex: -1, dataUnit: this._formEditorDataUnit, messagesBuilder: this.messagesBuilder, configManager: this._formEditorConfigManager, onConfigClose: () => this._formEditorConfigManager = undefined }));
    }
    if (!this.dataUnit || !((_a = this._configManager) === null || _a === void 0 ? void 0 : _a.isLoaded)) {
      return undefined;
    }
    const showTabs = this._guides && this._guides.length > 0;
    const fixedFormsParams = {
      formConfig: this.masterFormConfig,
      formMetadata: this._masterFormMetadata,
      selectedForm: (_b = this.selectedGuide) === null || _b === void 0 ? void 0 : _b.id,
      mainFormName: this._mainFormName,
      dataUnit: this.dataUnit,
      recordsValidator: this.recordsValidator,
      fieldToFocus: this._fieldToGetFocus,
      onRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this),
      propsCustomEditor: this._customEditors,
      fieldsProps: this._fieldsProps,
      entityPath: this.entityPath,
      fieldSearch: this._fieldSearch,
      onMainFormRef: (ref) => { this._mainForm = ref; }
    };
    return (h("section", { class: "snk-guides-viewer", ref: (ref) => {
        if (ref)
          this._container = ref;
      }, tabindex: -1 }, this.getTitle() && (h("div", { class: "ez-row snk-guides-viewer__header" }, h("div", { class: "snk-guides-viewer__header-breadcrumb ez-flex--align-items-center ez-flex-item--align-center", key: "header" }, h("div", { class: "ez-flex ez-flex--column ez-flex-item--auto" }, h("h1", { class: "ez-title ez-title--primary ez-title--xlarge", title: this.getTitleTooltip() }, this.getTitle()))))), h("div", { class: "snk-guides-viewer__container" }, SnkDynaformGuidesViewer.buildMainForm(fixedFormsParams), showTabs &&
      h("ez-tabselector", Object.assign({ class: "snk-guides-viewer__tabselector", tabs: this.buildTabItems(), selectedTab: (_c = this.selectedGuide) === null || _c === void 0 ? void 0 : _c.id, onEzChange: (evt) => this.onTabChange(evt.detail) }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${ElementIDUtils.getInternalIDInfo("tabselector")}` })), h("div", { class: "snk-guides-viewer__detail-container" }, SnkDynaformGuidesViewer.buildFixedForms(fixedFormsParams), this.getContent())), h("snk-configurator", { ref: (ref) => {
        if (ref)
          this._snkConfigurator = ref;
      }, viewMode: this.getConfigViewMode(), onConfigSelected: (evt) => this.changeConfigViewMode(evt.detail), messagesBuilder: this.messagesBuilder, onOpenConfig: (evt) => this.openConfig(evt.detail), resourceID: this.resourceID })));
  }
  get _element() { return getElement(this); }
  static get watchers() { return {
    "dataUnit": ["observeDataUnit"],
    "_formEditorConfigManager": ["observeFormConfigManager"],
    "dataState": ["observeDataState"],
    "masterFormConfig": ["observeMasterFormConfig"]
  }; }
};
var GUIDES_VIEWER_VIEW_MODE;
(function (GUIDES_VIEWER_VIEW_MODE) {
  GUIDES_VIEWER_VIEW_MODE[GUIDES_VIEWER_VIEW_MODE["GUIDES"] = 0] = "GUIDES";
  GUIDES_VIEWER_VIEW_MODE[GUIDES_VIEWER_VIEW_MODE["CONFIG"] = 1] = "CONFIG";
})(GUIDES_VIEWER_VIEW_MODE || (GUIDES_VIEWER_VIEW_MODE = {}));
SnkDynaformGuidesViewer.style = snkDynaformGuidesViewCss;

export { SnkDynaformGuidesViewer as S, SnkFormConfigManager as a };
