import { r as registerInstance, e as createEvent, h, F as Fragment, g as getElement } from './index-e9c7ceaa.js';
import { ObjectUtils, StringUtils, Action, KeyboardManager, ElementIDUtils } from '@sankhyalabs/core';
import { S as SnkFormConfigManager } from './SnkFormConfigManager-28deba35.js';
import { buildFormMetadata, FormMetadata } from '@sankhyalabs/ezui/dist/collection/utils/form';
import { T as TaskbarProcessor } from './taskbar-processor-3436124c.js';
import { T as TaskbarElement } from './taskbar-elements-b3c5a3ce.js';
import { V as VIEW_MODE } from './constants-7b422de0.js';
import './DataFetcher-955ee53e.js';
import './ISave-c8bf12c4.js';
import { P as PresentationMode } from './index-b40568ff.js';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import './dataunit-fetcher-6cacb959.js';
import './filter-item-type.enum-d45e026f.js';
import './form-config-fetcher-baa89098.js';
import { SelectionMode } from '@sankhyalabs/core/dist/dataunit/DataUnit';
import { buildFieldSearch, SHORTCUT_SEARCH_FIELD } from '@sankhyalabs/ezui/dist/collection/utils';

const snkGuidesViewerCss = ".sc-snk-guides-viewer-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);--snk-guides-viewer__guide-navigator--width:340px;display:block}snk-form-view.sc-snk-guides-viewer{width:100%}.snk-guides-viewer.sc-snk-guides-viewer{position:relative;padding-left:0px;padding-top:0px;padding-right:var(--snk-guides-viewer--space-large);padding-bottom:var(--snk-guides-viewer--space-large)}.snk-guides-viewer__detail-container.sc-snk-guides-viewer{display:flex;row-gap:24px;flex-direction:column}.snk-guides-viewer__header.sc-snk-guides-viewer{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);min-height:var(--snk-guides-viewer__header--min-height);width:calc(100% + (var(--snk-guides-viewer--space-large) * 2));padding-left:var(--snk-guides-viewer--space-large);padding-right:var(--snk-guides-viewer--space-large);padding-top:var(--snk-guides-viewer--space-large);padding-bottom:var(--snk-guides-viewer--space-small);margin-left:calc(var(--snk-guides-viewer--space-large) * -1);margin-right:calc(var(--snk-guides-viewer--space-large) * -1);margin-bottom:var(--snk-guides-viewer--space-small)}.snk-guides-viewer__header-breadcrumb.sc-snk-guides-viewer{width:25%;display:flex}.snk-guides-viewer__header-taskbar.sc-snk-guides-viewer{width:75%}.snk-guides-viewer__container.sc-snk-guides-viewer{display:grid;grid-template-columns:minmax(0, auto) minmax(0, 100%);height:100%;column-gap:var(--snk-guides-viewer--space-large)}.snk-guides-viewer__guide-navigator.sc-snk-guides-viewer{position:sticky;top:calc(var(--snk-guides-viewer__header--min-height) + var(--snk-guides-viewer--space-small));height:calc(100vh - var(--snk-guides-viewer__header--min-height) - var(--snk-guides-viewer--space-large) - var(--snk-guides-viewer--space-small))}.snk-guides-viewer__guide-navigator[open].sc-snk-guides-viewer{width:var(--snk-guides-viewer__guide-navigator--width);max-width:var(--snk-guides-viewer__guide-navigator--width);min-width:var(--snk-guides-viewer__guide-navigator--width)}.snk-guides-viewer__detail-content.sc-snk-guides-viewer{min-height:100%;align-items:flex-start;align-content:flex-start}";

const FORM_NAME_PREFIX = "__FORM:";
const SnkGuidesViewer = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.snkMasterFormConfigChange = createEvent(this, "snkMasterFormConfigChange", 7);
    this.exit = createEvent(this, "exit", 7);
    this.actionClick = createEvent(this, "actionClick", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    this._guideBuilders = new Map();
    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._hasToCreateFieldSearch = true;
    this._breadcrumbItems = [];
    this._guides = undefined;
    this._formEditorConfigManager = undefined;
    this._formEditorDataUnit = undefined;
    this._fieldToGetFocus = undefined;
    this._customEditors = undefined;
    this._customRenders = undefined;
    this._fieldsProps = {};
    this._mainForm = undefined;
  }
  observeDataUnit() {
    this.loadGuides(true);
  }
  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() {
    this.loadGuides(this.noGuideSelected());
    this.snkMasterFormConfigChange.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) {
    const masterConfig = !detail || this._currentDetail == undefined;
    this._formEditorConfigManager = masterConfig ? this._configManager : this._currentDetail.formConfigManager;
    this._formEditorDataUnit = masterConfig ? this.dataUnit : this._currentDetail.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() {
    this._container.focus();
  }
  exitViewer() {
    if (!this.enableGridInsert && this.dataUnit.isDirty()) {
      this.dataUnit.cancelEdition({ after: () => this.exit.emit() });
    }
    else {
      this.exit.emit();
    }
  }
  onActionClick(evt) {
    if (evt.detail === TaskbarElement.CONFIGURATOR) {
      if (evt.target.dataset.taskbarOwner != "master") {
        this._snkConfigurator.open();
        evt.stopImmediatePropagation();
        evt.stopPropagation();
      }
    }
  }
  onContentCardChanged(evt) {
    SnkGuidesViewer.updateContentCard(evt.detail.formName, evt.detail.cardConfig, evt.detail.propertyChanged, this._configManager)
      .then(() => this.masterFormConfig = this._configManager.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;
    if (this.dataUnit.isMultipleEdition) {
      const selectedRecords = (_b = (_a = this.dataUnit.getSelectionInfo()) === null || _a === void 0 ? void 0 : _a.records) !== null && _b !== void 0 ? _b : [];
      return this.messagesBuilder.getMessage("snkCrud.multipleEdition.editing", { COUNT: selectedRecords.length });
    }
    return this.messagesBuilder.getMessage(key, this.dataUnit.getSelectedRecord());
  }
  loadGuides(changeSelection) {
    if (!this.dataUnit) {
      return;
    }
    if (!this._configManager.isLoaded) {
      return;
    }
    this._masterFormMetadata = buildFormMetadata(this.masterFormConfig, this.dataUnit, true);
    const allSheets = this._masterFormMetadata.getAllSheets();
    const currentRecord = this.dataUnit.getSelectedRecord();
    const disableDetails = this.hasToDisableDetails(currentRecord);
    const guides = [];
    Array.from(allSheets.values()).forEach((sheet) => {
      const item = { id: sheet.name, label: sheet.label };
      if (this.isDetail(sheet.name) && disableDetails) {
        item.tooltip = this.getMessage("snkCrud.detail.tooltip.needSingleSelection");
        item.disabled = true;
      }
      guides.push(item);
    });
    this._guides = guides;
    if (this._guideNavigator) {
      this._guideNavigator.updateItem(this._guides);
    }
    if (changeSelection) {
      this.selectedGuide = this._guides.length > 0 ? this._guides[0] : undefined;
    }
  }
  hasToDisableDetails(currentRecord) {
    return !currentRecord
      || this.dataUnit.isNewRecord(currentRecord.__record__id__)
      || this.dataUnit.isMultipleEdition;
  }
  isDetail(formId) {
    return FormMetadata.getDetailName(formId) != undefined;
  }
  updateGuide(guideBuilder) {
    this._guideBuilders.set(guideBuilder.id, guideBuilder);
    const guideItem = guideBuilder.buildGuideItem(this._guideBuilders);
    if (this._guideNavigator) {
      this._guideNavigator.updateItem(guideItem).then(() => {
        this._guideNavigator.getCurrentPath().then(breadcrumbs => {
          this._breadcrumbItems = breadcrumbs;
        });
      });
      this._guides = this._guides.map(guide => {
        if (guide.id === guideItem.id) {
          return Object.assign(Object.assign(Object.assign({}, guide), guideItem), (guideItem.children !== undefined ? {} : { children: undefined }));
        }
        return guide;
      });
    }
  }
  getTaskBarId() {
    var _a;
    if ((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.isDirty) {
      return TASKBAR_ID.FINISH_EDITION;
    }
    if (this.dataUnit.isMultipleEdition) {
      return TASKBAR_ID.MUTIPLE_EDITION;
    }
    return TASKBAR_ID.REGULAR;
  }
  loadTaskbarProcessor() {
    const taskbarIDs = {};
    taskbarIDs[TASKBAR_ID.REGULAR] = this.buildBtnsRegularMode();
    taskbarIDs[TASKBAR_ID.FINISH_EDITION] = [TaskbarElement.CANCEL, TaskbarElement.SAVE, this.handleAddGridMode()];
    taskbarIDs[TASKBAR_ID.MUTIPLE_EDITION] = [TaskbarElement.CANCEL];
    this._taskbarProcessor = new TaskbarProcessor(taskbarIDs);
    this._taskbarProcessor.process(this.getTaskBarId(), this.taskbarManager, this.dataState, this.buildDisabledButtons(), this.buildInvisibleButtons());
  }
  buildBtnsRegularMode() {
    var _a, _b;
    const btnsRegularMode = [
      TaskbarElement.ATTACH, TaskbarElement.CLONE, TaskbarElement.REMOVE, TaskbarElement.MORE_OPTIONS,
      TaskbarElement.ACTIONS_BUTTON, TaskbarElement.DIVIDER, TaskbarElement.GRID_MODE, TaskbarElement.CONFIGURATOR,
    ];
    if (((_b = (_a = this.dataState) === null || _a === void 0 ? void 0 : _a.selectionInfo) === null || _b === void 0 ? void 0 : _b.length) <= 1) {
      btnsRegularMode.unshift(TaskbarElement.PREVIOUS, TaskbarElement.NEXT, TaskbarElement.DIVIDER);
    }
    if (this.presentationMode == PresentationMode.SECONDARY) {
      btnsRegularMode.unshift(TaskbarElement.INSERT);
    }
    else {
      btnsRegularMode.push(TaskbarElement.INSERT);
    }
    return btnsRegularMode;
  }
  buildDisabledButtons() {
    var _a, _b, _c, _d, _e, _f;
    const disabledButtons = [];
    if (!((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.hasPrevious))
      disabledButtons.push(TaskbarElement.PREVIOUS);
    if (!((_b = this.dataState) === null || _b === void 0 ? void 0 : _b.hasNext))
      disabledButtons.push(TaskbarElement.NEXT);
    if (((_d = (_c = this.dataState) === null || _c === void 0 ? void 0 : _c.selectionInfo) === null || _d === void 0 ? void 0 : _d.length) > 1)
      disabledButtons.push(TaskbarElement.CLONE);
    if ((_f = (_e = this.dataState) === null || _e === void 0 ? void 0 : _e.selectionInfo) === null || _f === void 0 ? void 0 : _f.isAllRecords())
      disabledButtons.push(TaskbarElement.REMOVE);
    return disabledButtons;
  }
  handleAddGridMode() {
    return this.enableGridInsert ? TaskbarElement.GRID_MODE : "";
  }
  buildInvisibleButtons() {
    const invisibleButtons = [];
    if (this.dataState && this.dataState.selectionInfo.mode === SelectionMode.ALL_RECORDS)
      invisibleButtons.push(TaskbarElement.ACTIONS_BUTTON);
    return invisibleButtons;
  }
  static updateContentCard(formName, cardConfig, propertyChanged, configManager) {
    return configManager.saveCardState(formName, cardConfig, propertyChanged);
  }
  static buildFixedForms(params) {
    var _a;
    const cardsState = (_a = params.formConfig) === null || _a === void 0 ? void 0 : _a.cardsState;
    if (cardsState == undefined) {
      return;
    }
    return (h(Fragment, null, Array.from(cardsState.entries())
      .filter(([formName, cardConfig]) => (cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.fixed) && formName != params.selectedForm)
      .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;
    })
      .map(([formName, cardConfig]) => {
      var _a, _b;
      const sheet = params.formMetadata.getSheet(formName);
      if (sheet == undefined) {
        return;
      }
      return h("snk-form-view", { levelPath: params.levelPath, label: sheet.label, name: formName, fields: sheet.fields, formMetadata: params.formMetadata, dataUnit: params.dataUnit, recordsValidator: params.recordsValidator, contracted: (cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.presentation) === "CONTRACTED", fixed: cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.fixed, summaryFields: (_b = (_a = params.formConfig) === null || _a === void 0 ? void 0 : _a.summary) === null || _b === void 0 ? void 0 : _b.get(formName), 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 });
    })));
  }
  wrapDetail(levels, content) {
    if (levels.length === 0) {
      return content;
    }
    const currentLevel = levels.pop();
    const childEntityName = FormMetadata.getDetailName(currentLevel);
    if (childEntityName) {
      return this.wrapDetail(levels, h("snk-data-unit", { dataUnitName: `${this.getDataUnitName(levels, childEntityName)}`, entityName: childEntityName }, content));
    }
  }
  getDataUnitName(levels, entityName) {
    if (levels.length > 0) {
      const entityNames = levels.map(level => FormMetadata.getDetailName(level));
      return `${this.entityPath}/${entityNames.join("/")}/${entityName}`;
    }
    return `${this.entityPath}/${entityName}`;
  }
  getContent() {
    var _a, _b, _c, _d, _e;
    if (!this.selectedGuide) {
      return;
    }
    const guideId = this.selectedGuide.id;
    let content;
    const levels = guideId.split("::");
    const currentLevel = levels.pop();
    const childEntityName = FormMetadata.getDetailName(currentLevel);
    let detailId = guideId;
    if (childEntityName || levels.length > 0) {
      let formName;
      let detailBranch;
      if (guideId.includes(FORM_NAME_PREFIX)) {
        [detailId, formName] = guideId.split(FORM_NAME_PREFIX);
        const pathSize = ((_a = this._breadcrumbItems) === null || _a === void 0 ? void 0 : _a.length) || 0;
        detailBranch = pathSize > 1 ? this._breadcrumbItems[pathSize - 2] : this.selectedGuide;
      }
      else {
        detailBranch = this.selectedGuide;
      }
      content = this.wrapDetail(levels, h("snk-detail-view", { ref: (ref) => this._currentDetail = ref, dataUnitName: this.getDataUnitName(levels, childEntityName), onSnkDetailGuidesChange: (evt) => this.updateGuide(evt.detail), entityName: childEntityName, selectedForm: formName, branchGuide: detailBranch, guideItemPath: this._breadcrumbItems, key: `detail${detailId}`, canEdit: this.canEdit, onSnkSwitchGuide: evt => this._guideNavigator.selectGuide(evt.detail), resourceID: this.resourceID, taskbarCustomContainerId: this.detailTaskbarCustomContainerId, customEditors: this._customEditors, customRenders: this._customRenders, presentationMode: this.presentationMode }));
    }
    else {
      const cardId = this.selectedGuide.id;
      const sheet = this._masterFormMetadata.getSheet(cardId);
      if (sheet) {
        const cardConfig = (_c = (_b = this.masterFormConfig) === null || _b === void 0 ? void 0 : _b.cardsState) === null || _c === void 0 ? void 0 : _c.get(cardId);
        content = h("snk-form-view", { ref: ref => this._mainForm = ref, fixed: cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.fixed, summaryFields: (_e = (_d = this.masterFormConfig) === null || _d === void 0 ? void 0 : _d.summary) === null || _e === void 0 ? void 0 : _e.get(cardId), name: cardId, 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 }, this.presentationMode == PresentationMode.SECONDARY && this.buildTaskBar());
      }
    }
    return content;
  }
  onBreadcrumbClickHandler(item) {
    if ((item === null || item === void 0 ? void 0 : item.id) == undefined) {
      return;
    }
    this._guideNavigator.selectGuide(item.id);
  }
  updateSelectedGuideHandler(currentItem) {
    this._guideHasChanged = this.selectedGuide != currentItem;
    this.selectedGuide = currentItem;
    this._guideNavigator.getCurrentPath().then(breadcrumbs => {
      this._breadcrumbItems = breadcrumbs;
    });
    this.resetGuideBadge(currentItem);
  }
  changeGuideHandler(guideName) {
    var _a;
    (_a = this._guideNavigator) === null || _a === void 0 ? void 0 : _a.selectGuide(guideName);
  }
  clearFieldToFocusHandler() {
    this._fieldToGetFocus = undefined;
  }
  resetGuideBadge(selectedGuide) {
    var _a;
    this._guides = [...(_a = this._guides) === null || _a === void 0 ? void 0 : _a.map(guide => {
        if (this.canClearGuideBadge(guide, selectedGuide.id)) {
          return Object.assign(Object.assign({}, guide), { badge: null });
        }
        return guide;
      })];
  }
  canClearGuideBadge(guide, idToCheck) {
    return (guide.id === idToCheck) || this.isIncludedInChildrenList(guide, idToCheck);
  }
  isIncludedInChildrenList(guide, guideId) {
    return this.hasChildren(guide) && this.getChildrenIdList(guide).includes(guideId);
  }
  hasChildren(guide) {
    return guide.children && Array.isArray(guide.children);
  }
  getChildrenIdList(guide) {
    return (guide.children).map(guideChild => guideChild.id);
  }
  getConfigViewMode() {
    return VIEW_MODE.GRID;
  }
  changeConfigViewMode(mode) {
    if (this._currentDetail) {
      this._currentDetail.changeViewMode(mode);
    }
  }
  openConfig(mode) {
    this._snkConfigurator.close();
    if (this._currentDetail) {
      if (mode === VIEW_MODE.FORM) {
        this.showFormConfig(true);
      }
      else {
        this._currentDetail.configGrid();
      }
    }
  }
  noGuideSelected() {
    var _a;
    return this.selectedGuide === undefined || '__main' === ((_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.id);
  }
  addFormLegacyConfigName() {
    if (this.formLegacyConfigName) {
      this._configManager.addFormLegacyConfig(this.formLegacyConfigName);
    }
  }
  setMasterFormConfig(config) {
    this.masterFormConfig = config;
  }
  componentWillLoad() {
    if (this.resourceID == undefined) {
      throw new Error(this.getMessage("snkCrud.errors.resourceIDNotProvided"));
    }
    this._configManager = new SnkFormConfigManager(this.configName, this.resourceID, this.setMasterFormConfig.bind(this), this.dataUnit);
    this.addFormLegacyConfigName();
    this._configManager.loadConfig();
  }
  componentDidRender() {
    if (!this._guideHasChanged) {
      return;
    }
    window.scrollTo(0, 0);
    this._guideHasChanged = false;
  }
  getFieldsSearch(item) {
    if (this._fieldSearch == undefined || this._hasToCreateFieldSearch) {
      this._hasToCreateFieldSearch = false;
      this._fieldSearch = buildFieldSearch(item, ({ argument }) => this.fieldsOptionLoader(argument), (option) => this.onSelectField(option));
    }
    return this._fieldSearch;
  }
  fieldsOptionLoader(argument) {
    return Promise.resolve(this._configManager.getFieldsList(argument)
      .map(field => ({ value: field.name, label: field.label })));
  }
  onSelectField(option) {
    if (option == undefined) {
      return;
    }
    this._fieldToGetFocus = option.value;
    const fieldGuideName = this.getGuideName(option.value);
    if (fieldGuideName !== this.selectedGuide.id) {
      this.changeGuideHandler(fieldGuideName);
    }
  }
  getActionsList() {
    var _a;
    const hardList = [];
    if (this.taskbarManager != undefined && this.taskbarManager.getMoreOptions != undefined) {
      return hardList.concat((_a = this.taskbarManager.getMoreOptions(this.getTaskBarId(), this.configName, this.dataState, this.actionsList)) !== null && _a !== void 0 ? _a : []);
    }
    return hardList.concat(this.actionsList);
  }
  getSettingsListForm() {
    const hardList = [{
        value: StringUtils.generateUUID(),
        label: this.getMessage("snkCrud.findColumn"),
        disableCloseOnSelect: true,
        eagerInitialize: true,
        itemBuilder: (_, item) => this.getFieldsSearch(item)
      }];
    return hardList;
  }
  buildTaskBar() {
    var _a;
    return h("div", { class: `snk-guides-viewer__header-taskbar ${this.presentationMode != PresentationMode.SECONDARY ? 'ez-align--right' : 'ez-padding-bottom--medium'}` }, h("snk-taskbar", { key: "guideViewerTaskbar", "data-element-id": "guideViewer", configName: this.configName, buttons: this._taskbarProcessor.buttons, disabledButtons: this._taskbarProcessor.disabledButtons, customButtons: this._taskbarProcessor.customButtons, actionsList: this.getActionsList(), actionsSettingsList: this.getSettingsListForm(), messagesBuilder: this.messagesBuilder, presentationMode: this.presentationMode, primaryButton: ((_a = this.dataState) === null || _a === void 0 ? void 0 : _a.isDirty) ? TaskbarElement.SAVE : TaskbarElement.INSERT, "data-taskbar-owner": "master", dataUnit: this.dataUnit, resourceID: this.resourceID, customSlotId: "GUIDES_VIEWER_TASKBAR_CUSTOM_ELEMENTS", alignRigth: true }, h("slot", { name: "GUIDES_VIEWER_TASKBAR_CUSTOM_ELEMENTS" })));
  }
  async dataUnitActionHandler(action) {
    var _a;
    switch (action.type) {
      case Action.EDITION_CANCELED:
      case Action.DATA_SAVED:
        if (this.dataUnit.isMultipleEdition) {
          this.exitViewer();
          this.dataUnit.isMultipleEdition = false;
        }
        break;
      case Action.FIELD_INVALIDATED:
        const guideName = this.getGuideName((_a = action.payload) === null || _a === void 0 ? void 0 : _a.fieldName);
        await this.addErrorBadgeToGuide(guideName);
        await this.openGuideNavigator(guideName);
        break;
      case Action.METADATA_LOADED:
      case Action.MULTIPLE_EDITION_CHANGED:
        this.loadGuides(this.noGuideSelected());
        break;
    }
  }
  async addErrorBadgeToGuide(guideName) {
    var _a;
    this._guides = [...(_a = this._guides) === null || _a === void 0 ? void 0 : _a.map(guide => {
        return Object.assign(Object.assign({}, guide), { badge: this.getBadge(guide, guideName) });
      })];
  }
  async openGuideNavigator(guideName) {
    if (this.selectedGuide.id !== guideName) {
      await this._guideNavigator.openGuideNavidator();
    }
  }
  getBadge(guide, tabName) {
    var _a;
    if (this.selectedGuide.id === tabName) {
      return null;
    }
    if (tabName === guide.id) {
      return "error";
    }
    return (_a = guide.badge) !== null && _a !== void 0 ? _a : null;
  }
  getGuideName(fieldName) {
    var _a;
    for (const sheet of this._masterFormMetadata.getAllSheets()) {
      const formFields = (_a = sheet[1]) === null || _a === void 0 ? void 0 : _a.fields;
      for (const field of formFields) {
        if (field.name === fieldName) {
          return sheet[0];
        }
      }
    }
    return "";
  }
  getTitle() {
    var _a, _b;
    return (_b = (_a = this.getCustomTitle) === null || _a === void 0 ? void 0 : _a.call(this)) !== null && _b !== void 0 ? _b : this.getMessage("snkCrud.title");
  }
  getTitleTooltip() {
    if (!this.dataUnit.isMultipleEdition)
      return;
    return this.buildRecordIdsArray();
  }
  buildRecordIdsArray() {
    var _a, _b;
    const selectedRecords = (_b = (_a = this.dataUnit.getSelectionInfo()) === null || _a === void 0 ? void 0 : _a.records) !== null && _b !== void 0 ? _b : [];
    if (selectedRecords.length === 0) {
      return "[]";
    }
    const labels = selectedRecords.map(record => this.messagesBuilder.getMessage("snkCrud.title", record));
    return `[${labels.join(", ")}]`;
  }
  componentDidLoad() {
    this.dataUnit.subscribe(this.dataUnitActionHandler.bind(this));
    this.initKeyboardManager();
  }
  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 });
    this._keyboardManager.bind(SHORTCUT_SEARCH_FIELD, async () => {
      if (!this._mainForm)
        return;
      await this._mainForm.showSearchField();
    }, { description: this.getMessage("snkSimpleCrud.findFields"), element: this._element });
  }
  render() {
    var _a, _b;
    if (this._formEditorConfigManager != undefined) {
      return (h("snk-form-config", { ref: ref => this._container = ref, tabindex: -1, dataUnit: this._formEditorDataUnit, messagesBuilder: this.messagesBuilder, configManager: this._formEditorConfigManager, onConfigClose: () => this._formEditorConfigManager = null }));
    }
    if (!this.dataUnit || !this._configManager.isLoaded) {
      return;
    }
    this.loadTaskbarProcessor();
    const showGuides = this._guides && (this._guides.length > 1);
    return (h("section", { class: "snk-guides-viewer", ref: ref => this._container = ref, tabindex: -1 }, 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 ez-padding-left--large", key: "header" }, h("ez-button", { onClick: () => this.exitViewer(), title: this.getMessage("snkCrud.goBackTitle"), mode: "icon", iconName: "arrow_back", class: "ez-padding-right--medium", size: "small" }), 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()), ((_a = this._breadcrumbItems) === null || _a === void 0 ? void 0 : _a.length) > 1 &&
      h("div", { class: "ez-margin-top--extra-small" }, h("ez-breadcrumb", Object.assign({ items: this._breadcrumbItems, onSelectedItem: (evt) => this.onBreadcrumbClickHandler(evt === null || evt === void 0 ? void 0 : evt.detail) }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${ElementIDUtils.getInternalIDInfo("breadcrumb")}` }))))), this.presentationMode != PresentationMode.SECONDARY && this.buildTaskBar()), h("div", { class: "snk-guides-viewer__container" }, showGuides ?
      h("ez-guide-navigator", { ref: (ref) => this._guideNavigator = ref, class: "snk-guides-viewer__guide-navigator", items: this._guides, selectedId: this.selectedGuide ? this.selectedGuide.id : undefined, onEzSelectionChange: evt => this.updateSelectedGuideHandler(evt.detail) })
      :
        h("div", null), h("div", { class: "snk-guides-viewer__detail-container" }, SnkGuidesViewer.buildFixedForms({
      formConfig: this.masterFormConfig,
      formMetadata: this._masterFormMetadata,
      selectedForm: (_b = this.selectedGuide) === null || _b === void 0 ? void 0 : _b.id,
      dataUnit: this.dataUnit,
      recordsValidator: this.recordsValidator,
      fieldToFocus: this._fieldToGetFocus,
      onRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this),
      propsCustomEditor: this._customEditors,
      fieldsProps: this._fieldsProps
    }), this.getContent())), h("snk-configurator", { ref: (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"],
    "dataState": ["observeDataState"],
    "masterFormConfig": ["observeMasterFormConfig"]
  }; }
};
var TASKBAR_ID;
(function (TASKBAR_ID) {
  TASKBAR_ID["FINISH_EDITION"] = "snkGuideViewer.finish_edition";
  TASKBAR_ID["MUTIPLE_EDITION"] = "snkGuideViewer.multiple_edition";
  TASKBAR_ID["REGULAR"] = "snkGuideViewer.regular";
})(TASKBAR_ID || (TASKBAR_ID = {}));
SnkGuidesViewer.style = snkGuidesViewerCss;

export { SnkGuidesViewer as S };
