import { proxyCustomElement, HTMLElement, createEvent, h, Fragment, forceUpdate, Host } from '@stencil/core/internal/client';
import { ObjectUtils, StringUtils, Action, KeyboardManager, ElementIDUtils } from '@sankhyalabs/core';
import { S as SnkFormConfigManager } from './SnkFormConfigManager.js';
import { buildFormMetadata, FormMetadata } from '@sankhyalabs/ezui/dist/collection/utils/form';
import { S as SnkMessageBuilder } from './DataFetcher.js';
import { P as PresentationMode } 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 { T as TaskbarElement, d as defineCustomElement$5 } from './snk-taskbar2.js';
import { T as TaskbarProcessor } from './ContinuousInsertUtils.js';
import { SelectionMode } from '@sankhyalabs/core/dist/dataunit/DataUnit';
import { buildFieldSearch, SHORTCUT_SEARCH_FIELD } from '@sankhyalabs/ezui/dist/collection/utils';
import { d as defineCustomElement$F } from './config-header2.js';
import { d as defineCustomElement$E } from './configs-button2.js';
import { d as defineCustomElement$D } from './field-config2.js';
import { d as defineCustomElement$C } from './field-item2.js';
import { d as defineCustomElement$B } from './fields-layout2.js';
import { d as defineCustomElement$A } from './fields-selector2.js';
import { d as defineCustomElement$z } from './guides-configurator2.js';
import { d as defineCustomElement$y } from './snk-actions-button2.js';
import { d as defineCustomElement$x } from './snk-attach2.js';
import { d as defineCustomElement$w } from './snk-configurator2.js';
import { d as defineCustomElement$v } from './snk-data-exporter2.js';
import { d as defineCustomElement$u } from './snk-data-unit2.js';
import { d as defineCustomElement$t } from './snk-default-filter2.js';
import { d as defineCustomElement$s } from './snk-exporter-email-sender2.js';
import { d as defineCustomElement$r } from './snk-expression-group2.js';
import { d as defineCustomElement$q } from './snk-expression-item2.js';
import { d as defineCustomElement$p } from './snk-filter-advanced-mode2.js';
import { d as defineCustomElement$o } from './snk-filter-assistent-mode2.js';
import { d as defineCustomElement$n } from './snk-filter-bar2.js';
import { d as defineCustomElement$m } from './snk-filter-detail2.js';
import { d as defineCustomElement$l } from './snk-filter-field-search2.js';
import { d as defineCustomElement$k } from './snk-filter-item2.js';
import { d as defineCustomElement$j } from './snk-filter-modal2.js';
import { d as defineCustomElement$i } from './snk-filter-modal-item2.js';
import { d as defineCustomElement$h } from './snk-filter-param-config2.js';
import { d as defineCustomElement$f } from './snk-form-summary2.js';
import { d as defineCustomElement$e } from './snk-form-view2.js';
import { d as defineCustomElement$d } from './snk-grid2.js';
import { d as defineCustomElement$c } from './snk-grid-config2.js';
import { d as defineCustomElement$b } from './snk-layout-form-config2.js';
import { d as defineCustomElement$a } from './snk-personalized-filter2.js';
import { d as defineCustomElement$9 } from './snk-select-box2.js';
import { d as defineCustomElement$8 } from './snk-simple-bar2.js';
import { d as defineCustomElement$7 } from './snk-simple-crud2.js';
import { d as defineCustomElement$6 } from './snk-simple-form-config2.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';
import { d as defineCustomElement$g } from './snk-form-config2.js';

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 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    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 this; }
  static get watchers() { return {
    "dataUnit": ["observeDataUnit"],
    "dataState": ["observeDataState"],
    "masterFormConfig": ["observeMasterFormConfig"]
  }; }
  static get style() { return snkGuidesViewerCss; }
}, [6, "snk-guides-viewer", {
    "dataUnit": [16],
    "dataState": [16],
    "configName": [1, "config-name"],
    "entityPath": [1, "entity-path"],
    "actionsList": [16],
    "recordsValidator": [16],
    "masterFormConfig": [1040],
    "selectedGuide": [1040],
    "taskbarManager": [16],
    "messagesBuilder": [1040],
    "canEdit": [4, "can-edit"],
    "presentationMode": [1, "presentation-mode"],
    "resourceID": [1, "resource-i-d"],
    "detailTaskbarCustomContainerId": [1, "detail-taskbar-custom-container-id"],
    "formLegacyConfigName": [1, "form-legacy-config-name"],
    "enableGridInsert": [4, "enable-grid-insert"],
    "ignoreReadOnlyFormFields": [4, "ignore-read-only-form-fields"],
    "getCustomTitle": [16],
    "_hasToCreateFieldSearch": [32],
    "_breadcrumbItems": [32],
    "_guides": [32],
    "_formEditorConfigManager": [32],
    "_formEditorDataUnit": [32],
    "_fieldToGetFocus": [32],
    "_customEditors": [32],
    "_customRenders": [32],
    "_fieldsProps": [32],
    "_mainForm": [32],
    "showFormConfig": [64],
    "addCustomEditor": [64],
    "addGridCustomRender": [64],
    "setFieldProp": [64],
    "setFocus": [64]
  }, [[2, "actionClick", "onActionClick"], [0, "snkContentCardChanged", "onContentCardChanged"]]]);
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 = {}));
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-guides-viewer", "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-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-layout-form-config", "snk-personalized-filter", "snk-select-box", "snk-simple-bar", "snk-simple-crud", "snk-simple-form-config", "snk-taskbar", "snk-view-representation", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-guides-viewer":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkGuidesViewer);
      }
      break;
    case "config-header":
      if (!customElements.get(tagName)) {
        defineCustomElement$F();
      }
      break;
    case "configs-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$E();
      }
      break;
    case "field-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$D();
      }
      break;
    case "field-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$C();
      }
      break;
    case "fields-layout":
      if (!customElements.get(tagName)) {
        defineCustomElement$B();
      }
      break;
    case "fields-selector":
      if (!customElements.get(tagName)) {
        defineCustomElement$A();
      }
      break;
    case "guides-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$z();
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$y();
      }
      break;
    case "snk-attach":
      if (!customElements.get(tagName)) {
        defineCustomElement$x();
      }
      break;
    case "snk-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$w();
      }
      break;
    case "snk-data-exporter":
      if (!customElements.get(tagName)) {
        defineCustomElement$v();
      }
      break;
    case "snk-data-unit":
      if (!customElements.get(tagName)) {
        defineCustomElement$u();
      }
      break;
    case "snk-default-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$t();
      }
      break;
    case "snk-detail-view":
      if (!customElements.get(tagName)) {
        defineCustomElement();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$s();
      }
      break;
    case "snk-expression-group":
      if (!customElements.get(tagName)) {
        defineCustomElement$r();
      }
      break;
    case "snk-expression-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$q();
      }
      break;
    case "snk-filter-advanced-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$p();
      }
      break;
    case "snk-filter-assistent-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$o();
      }
      break;
    case "snk-filter-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$n();
      }
      break;
    case "snk-filter-detail":
      if (!customElements.get(tagName)) {
        defineCustomElement$m();
      }
      break;
    case "snk-filter-field-search":
      if (!customElements.get(tagName)) {
        defineCustomElement$l();
      }
      break;
    case "snk-filter-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$k();
      }
      break;
    case "snk-filter-modal":
      if (!customElements.get(tagName)) {
        defineCustomElement$j();
      }
      break;
    case "snk-filter-modal-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$i();
      }
      break;
    case "snk-filter-param-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$h();
      }
      break;
    case "snk-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$g();
      }
      break;
    case "snk-form-summary":
      if (!customElements.get(tagName)) {
        defineCustomElement$f();
      }
      break;
    case "snk-form-view":
      if (!customElements.get(tagName)) {
        defineCustomElement$e();
      }
      break;
    case "snk-grid":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-layout-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-personalized-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-simple-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-simple-crud":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-simple-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-taskbar":
      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;
  } });
}

class GuideBuilder {
  constructor(parentGuide, formMetadata, dataUnit, messageBuilder) {
    this._parentGuide = parentGuide;
    this._formMetadata = formMetadata;
    this._dataUnit = dataUnit;
    this._messageBuilder = messageBuilder;
    if (!this._messageBuilder) {
      this._messageBuilder = new SnkMessageBuilder();
    }
  }
  get id() {
    return this._parentGuide.id;
  }
  getMessage(key, params) {
    return this._messageBuilder.getMessage(key, params);
  }
  buildGuideItem(detailBuilders) {
    const item = Object.assign({}, this._parentGuide);
    delete item.expanded;
    delete item.children;
    const currentRecord = this._dataUnit.getSelectedRecord();
    if (!currentRecord) {
      return item;
    }
    const isNewRecord = this._dataUnit.isNewRecord(currentRecord.__record__id__);
    const children = Array.from(this._formMetadata.getAllSheets().values()).map((sheet) => {
      const { name, label } = sheet;
      const isDetail = FormMetadata.getDetailName(name.split("::").pop()) != undefined;
      const disabled = isDetail && isNewRecord;
      const parentId = this._parentGuide.id;
      const id = isDetail ? `${parentId}::${name}` : `${parentId}__FORM:${name}`;
      if (isDetail && detailBuilders.has(id) && !disabled) {
        const item = detailBuilders.get(id).buildGuideItem(detailBuilders);
        return item;
      }
      return {
        id,
        label,
        disabled,
        tooltip: disabled ? this.getMessage("snkCrud.guide.tooltip.disabledDetail") : undefined
      };
    });
    const newGuideItem = children.shift();
    newGuideItem.label = isNewRecord ? this.getMessage("snkCrud.title.newRecord") : currentRecord.__record__label__;
    newGuideItem.children = children;
    item.children = [newGuideItem];
    return item;
  }
}

const snkDetailViewCss = ".sc-snk-detail-view-h{display:flex;row-gap:24px;flex-direction:column;width:100%;height:100%}.level-path.sc-snk-detail-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.form-taskbar.sc-snk-detail-view{padding-bottom:var(--space--medium)}.grid-container.sc-snk-detail-view{background-color:#FFF;min-height:100px;height:100%}.detail-header.sc-snk-detail-view{padding-bottom:0}snk-data-unit.sc-snk-detail-view{flex:1}snk-grid.sc-snk-detail-view{height:calc(100% - 43px)}";

const SnkDetailView = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.snkDetailGuidesChange = createEvent(this, "snkDetailGuidesChange", 7);
    this.snkSwitchGuide = createEvent(this, "snkSwitchGuide", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    this._disabledButtons = undefined;
    this._currentView = undefined;
    this.attachmentRegisterKey = undefined;
    this._fieldToGetFocus = undefined;
    this._hasToCreateFieldSearch = true;
    this.formConfigManager = undefined;
    this.dataUnitName = undefined;
    this.resourceID = undefined;
    this.guideItemPath = undefined;
    this.entityName = undefined;
    this.label = undefined;
    this.dataUnit = undefined;
    this.selectedForm = undefined;
    this.dataState = undefined;
    this.messagesBuilder = undefined;
    this.branchGuide = undefined;
    this.canEdit = true;
    this.taskbarCustomContainerId = undefined;
    this.customEditors = undefined;
    this.customRenders = undefined;
    this.presentationMode = PresentationMode.SECONDARY;
  }
  observeDataUnit(newDataUnit, oldDataUnit) {
    newDataUnit === null || newDataUnit === void 0 ? void 0 : newDataUnit.subscribe(this.dataUnitActionHandler.bind(this));
    oldDataUnit === null || oldDataUnit === void 0 ? void 0 : oldDataUnit.unsubscribe(this.dataUnitActionHandler);
  }
  observerDataState(newValue, oldValue) {
    const openInsertion = !(oldValue === null || oldValue === void 0 ? void 0 : oldValue.insertionMode) && (newValue === null || newValue === void 0 ? void 0 : newValue.insertionMode);
    const closeInsertion = (oldValue === null || oldValue === void 0 ? void 0 : oldValue.insertionMode) && !(newValue === null || newValue === void 0 ? void 0 : newValue.insertionMode);
    if (openInsertion || closeInsertion) {
      this.loadMetadata();
    }
    if (this._formMetadata == undefined) {
      return;
    }
    const newRecord = newValue === null || newValue === void 0 ? void 0 : newValue.selectedRecord;
    const oldRecord = oldValue === null || oldValue === void 0 ? void 0 : oldValue.selectedRecord;
    if ((newRecord === null || newRecord === void 0 ? void 0 : newRecord.__record__id__) !== (oldRecord === null || oldRecord === void 0 ? void 0 : oldRecord.__record__id__)) {
      this.snkDetailGuidesChange.emit(new GuideBuilder(this.branchGuide, this._formMetadata, this.dataUnit, this.messagesBuilder));
    }
    if (openInsertion) {
      setTimeout(() => {
        //FIXME: A necessidade de usar esse timeout é por causa da renderização
        //do guide navigator... se esse evento subir antes do guidenavigator ter
        //um item com esse id, ele fica sem seleção. Acredito que poderíamos
        //ajustar o componente para manter o item selecionado e então remover
        //esse timeout.
        this.changeViewMode(VIEW_MODE.FORM);
      }, 0);
    }
    if (closeInsertion) {
      this.changeViewMode(VIEW_MODE.GRID);
    }
    const disabledButtons = [];
    if (!this.dataState.hasPrevious) {
      disabledButtons.push(TaskbarElement.PREVIOUS);
    }
    if (!this.dataState.hasNext) {
      disabledButtons.push(TaskbarElement.NEXT);
    }
    if (this.dataState.insertionMode) {
      disabledButtons.push(TaskbarElement.INSERT);
    }
    this._disabledButtons = disabledButtons;
  }
  /**
  * Muda o modo de visualização do componente entre VIEW_MODE.GRID e VIEW_MODE.FORM
  * @param mode - Novo modo que o componente deve ser apresentado.
  */
  async changeViewMode(mode) {
    this.emitSwitchEvent(mode);
  }
  /**
   * Abre o configurador de grid.
   */
  async configGrid() {
    if (this._snkGrid) {
      this._snkGrid.showConfig();
    }
  }
  async showUp() {
    if (this._snkFormView) {
      this._snkFormView.showUp();
    }
    if (this._snkGrid) {
      this._snkGrid.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  }
  /**
   * Registra um editor customizado para campos da grade e formulário.
   */
  async addCustomEditor(fieldName, customEditor) {
    var _a;
    const detailContext = this.normalizeBranchGuideId((_a = this.branchGuide) === null || _a === void 0 ? void 0 : _a.id);
    this._snkGrid.addCustomEditor(fieldName, customEditor, detailContext);
    this._snkFormView.addCustomEditor(fieldName, customEditor, detailContext);
  }
  async observerPropsCustomEditor(newValue) {
    for (const fieldName in newValue) {
      await this.addCustomEditor(fieldName, newValue[fieldName]);
    }
  }
  /**
   * Registra um render customizado para colunas da grid.
   */
  async addGridCustomRender(fieldName, customRender) {
    var _a;
    const detailContext = this.normalizeBranchGuideId((_a = this.branchGuide) === null || _a === void 0 ? void 0 : _a.id);
    await this._snkGrid.addGridCustomRender(fieldName, customRender, detailContext);
  }
  onContentCardChanged(evt) {
    SnkGuidesViewer.updateContentCard(evt.detail.formName, evt.detail.cardConfig, evt.detail.propertyChanged, this.formConfigManager).then(() => forceUpdate(this));
    evt.stopPropagation();
  }
  async observeCustomRenders(newValue) {
    for (const field in newValue) {
      const customRender = newValue[field];
      await this.addGridCustomRender(field, customRender);
    }
  }
  updateLabel() {
    const guideItemPathSize = this.guideItemPath ? this.guideItemPath.length : 0;
    if (guideItemPathSize > 0) {
      const labels = guideItemPathSize > 0 ? this.guideItemPath.map(item => item.label) : undefined;
      this.label = labels.pop();
      this._levelPath = labels.length > 0 ? labels.join(" / ") : undefined;
    }
    else {
      this.label = "";
      this._levelPath = undefined;
    }
  }
  getFormGuideId(formName) {
    var _a;
    if (!formName) {
      const currentRecord = (_a = this.dataState) === null || _a === void 0 ? void 0 : _a.selectedRecord;
      if (currentRecord == undefined) {
        return;
      }
      const forms = Array.from(this._formMetadata.getAllSheets().keys());
      if (!forms || forms.length == 0) {
        return;
      }
      formName = forms[0];
    }
    return `${this.stripFormPattern(this.branchGuide.id)}__FORM:${formName}`;
  }
  stripFormPattern(guideId) {
    return guideId.replace(SnkDetailView.REGEX_FORM_ID, "");
  }
  loadMetadata() {
    if (!this.dataUnit) {
      return;
    }
    if (!this.formConfigManager.isLoaded) {
      return;
    }
    const formConfig = this.formConfigManager.getConfig(this.dataUnit);
    //this._cardsState = formConfig?.cardsState;
    this._formMetadata = buildFormMetadata(formConfig == undefined || formConfig.fields.length === 0 ? undefined : formConfig, this.dataUnit, true);
  }
  dataUnitReadyHandler(evt) {
    this.dataUnit = evt.detail;
    this.loadMetadata();
  }
  updateViewStack(viewStack) {
    var _a, _b;
    this._viewStack = viewStack;
    this._currentView = this.selectedForm ? 1 : 0;
    (_b = (_a = this._viewStack) === null || _a === void 0 ? void 0 : _a.show) === null || _b === void 0 ? void 0 : _b.call(_a, this._currentView);
  }
  getFormFields() {
    if (this.selectedForm && this._formMetadata) {
      return this._formMetadata.getSheet(this.selectedForm).fields;
    }
    return [];
  }
  emitSwitchEvent(mode) {
    const guideId = mode === VIEW_MODE.GRID ? this.stripFormPattern(this.branchGuide.id) : this.getFormGuideId();
    if (guideId) {
      this.snkSwitchGuide.emit(guideId);
    }
  }
  handleAttachBack() {
    this._viewStack.show(VIEW_MODE.GRID);
  }
  executeActionHandler(evt) {
    if (evt.detail === TaskbarElement.GRID_MODE) {
      this.emitSwitchEvent(VIEW_MODE.GRID);
      evt.stopPropagation();
    }
    if (evt.detail === TaskbarElement.FORM_MODE || evt.detail === TaskbarElement.UPDATE) {
      this.emitSwitchEvent(VIEW_MODE.FORM);
      evt.stopPropagation();
    }
    if (evt.detail === TaskbarElement.ATTACH) {
      this._viewStack.show(VIEW_MODE.ATTACHMENT);
      evt.stopPropagation();
    }
  }
  async getAttachmentRegisterKey() {
    if (!this._snkDataUnit)
      return;
    const recordCriteria = await this._snkDataUnit.getSelectedRecordsIDsInfo();
    const joinedPrimaryKeys = recordCriteria.map(({ value }) => value).join('_');
    return joinedPrimaryKeys;
  }
  async handleDataStateChange({ detail: dataState }) {
    this.dataState = dataState;
    if (dataState.selectedRecord !== undefined && this._snkDataUnit) {
      this.attachmentRegisterKey = await this.getAttachmentRegisterKey();
    }
  }
  componentWillLoad() {
    this._configName = `dynaform.${this.entityName}`;
    this.formConfigManager = new SnkFormConfigManager(this._configName, this.resourceID, () => this.loadMetadata(), this.dataUnit);
    this.formConfigManager.loadConfig();
    if (this.messagesBuilder == undefined) {
      this.messagesBuilder = new SnkMessageBuilder(this.entityName);
    }
  }
  async componentDidLoad() {
    await this.observerPropsCustomEditor(this.customEditors);
    await this.observeCustomRenders(this.customRenders);
    this.initKeyboardManager();
  }
  disconnectedCallback() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  async dataUnitActionHandler(action) {
    if (action.type === Action.FIELD_INVALIDATED) {
      this.addErrorBadgeToBranchGuide();
    }
  }
  addErrorBadgeToBranchGuide() {
    this.branchGuide = Object.assign(Object.assign({}, this.branchGuide), { badge: 'error' });
    this.snkDetailGuidesChange.emit(new GuideBuilder(this.branchGuide, this._formMetadata, this.dataUnit, this.messagesBuilder));
  }
  normalizeBranchGuideId(id) {
    return id === null || id === void 0 ? void 0 : id.replace(/child\[(.*?)\]/g, '$1').replace(/::/g, '>');
  }
  getSettingsListForm() {
    const hardList = [{
        value: StringUtils.generateUUID(),
        label: this.messagesBuilder.getMessage("snkCrud.findColumn", undefined),
        disableCloseOnSelect: true,
        eagerInitialize: true,
        itemBuilder: (_, item) => this.getFieldsSearch(item)
      }];
    return hardList;
  }
  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) {
    const searchTerm = argument === null || argument === void 0 ? void 0 : argument.toLowerCase();
    const allFields = this.getFormFields().map(field => { var _a; return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getField(field.name); });
    const filteredFields = allFields.filter(field => {
      var _a, _b;
      return ((_a = field.name) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(searchTerm)) ||
        ((_b = field.label) === null || _b === void 0 ? void 0 : _b.toLowerCase().includes(searchTerm));
    });
    const options = filteredFields.map(field => ({ value: field.name, label: field.label }));
    return Promise.resolve(options);
  }
  onSelectField(option) {
    if (option == undefined) {
      return;
    }
    this._fieldToGetFocus = option.value;
  }
  clearFieldToFocusHandler() {
    this._fieldToGetFocus = undefined;
  }
  async initKeyboardManager() {
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element });
    this._keyboardManager.bind(SHORTCUT_SEARCH_FIELD, async () => {
      await this._snkFormView.showSearchField();
    }, { description: this.messagesBuilder.getMessage("snkSimpleCrud.findFields"), element: this._element });
  }
  render() {
    this.updateLabel();
    //const cardConfig: IFormCardConfig = this._cardsState?.get(this.selectedForm);
    return (h(Host, null, h("snk-data-unit", { ref: (el) => this._snkDataUnit = el, dataUnitName: `${this.dataUnitName}`, onDataUnitReady: evt => this.dataUnitReadyHandler(evt), entityName: this.entityName, onDataStateChange: this.handleDataStateChange.bind(this), ignoreSaveMessage: this._currentView === VIEW_MODE.GRID, messagesBuilder: this.messagesBuilder, configName: this._configName }, h("ez-view-stack", { ref: (ref) => this.updateViewStack(ref) }, h("stack-item", null, h("div", { class: "ez-box ez-box--shadow grid-container" }, h("div", { class: "ez-title--primary ez-size-width--full ez-padding--large detail-header" }, h("div", { class: "ez-flex ez-text ez-text--bold ez-flex--justify-start ez-flex--align-items-center" }, this._levelPath ? h("span", { class: "level-path" }, this._levelPath + " /") : undefined, this.label)), h("snk-grid", { class: "ez-size-width--full", ref: (ref) => this._snkGrid = ref, configName: this._configName, messagesBuilder: this.messagesBuilder, onGridDoubleClick: () => this.emitSwitchEvent(VIEW_MODE.FORM), onActionClick: (evt) => this.executeActionHandler(evt), presentationMode: this.presentationMode, canEdit: this.canEdit, isDetail: true, taskbarCustomContainerId: this.taskbarCustomContainerId, gridHeaderCustomSlotId: "DETAIL_GRID_HEADER_CUSTOM_ELEMENTS", topTaskbarCustomSlotId: "DETAIL_GRID_TASKBAR_CUSTOM_ELEMENTS", outlineMode: false }))), h("stack-item", null, h("snk-form-view", { ref: (ref) => this._snkFormView = ref, canExpand: false, canFix: false, name: this.selectedForm, formMetadata: this._formMetadata, dataUnit: this.dataUnit, fields: this.getFormFields(), fieldToFocus: this._fieldToGetFocus, label: this.label, levelPath: this._levelPath, onFormItemsReady: ({ detail: formItems }) => this.formItemsReady.emit(formItems), onSnkRequestClearFieldToFocus: this.clearFieldToFocusHandler.bind(this), fieldSearch: this._fieldSearch }, h("snk-taskbar", { key: "guideViewerTaskbar", class: "form-taskbar", "data-element-id": "guideViewer", configName: this._configName, messagesBuilder: this.messagesBuilder, disabledButtons: this._disabledButtons, buttons: "INSERT,PREVIOUS,NEXT,DIVIDER,CLONE,REMOVE,MORE_OPTIONS,ACTIONS_BUTTON,DIVIDER,GRID_MODE,CONFIGURATOR", primaryButton: "INSERT", presentationMode: this.presentationMode, onActionClick: evt => this.executeActionHandler(evt), dataUnit: this.dataUnit, resourceID: this.resourceID, customContainerId: this.taskbarCustomContainerId, customSlotId: "DETAIL_TASKBAR_CUSTOM_ELEMENTS", actionsSettingsList: this.getSettingsListForm() }, h("slot", { name: "DETAIL_TASKBAR_CUSTOM_ELEMENTS" })))), h("stack-item", null, h("snk-attach", { registerKey: this.attachmentRegisterKey, messagesBuilder: this.messagesBuilder, entityName: this.entityName, onBack: this.handleAttachBack.bind(this) }))))));
  }
  get _element() { return this; }
  static get watchers() { return {
    "dataUnit": ["observeDataUnit"],
    "dataState": ["observerDataState"],
    "customEditors": ["observerPropsCustomEditor"],
    "customRenders": ["observeCustomRenders"]
  }; }
  static get style() { return snkDetailViewCss; }
}, [6, "snk-detail-view", {
    "formConfigManager": [1040],
    "dataUnitName": [1, "data-unit-name"],
    "resourceID": [1, "resource-i-d"],
    "guideItemPath": [16],
    "entityName": [1, "entity-name"],
    "label": [1],
    "dataUnit": [1040],
    "selectedForm": [1025, "selected-form"],
    "dataState": [1040],
    "messagesBuilder": [1040],
    "branchGuide": [1040],
    "canEdit": [4, "can-edit"],
    "taskbarCustomContainerId": [1, "taskbar-custom-container-id"],
    "customEditors": [16],
    "customRenders": [16],
    "presentationMode": [1, "presentation-mode"],
    "_disabledButtons": [32],
    "_currentView": [32],
    "attachmentRegisterKey": [32],
    "_fieldToGetFocus": [32],
    "_hasToCreateFieldSearch": [32],
    "changeViewMode": [64],
    "configGrid": [64],
    "showUp": [64],
    "addCustomEditor": [64],
    "addGridCustomRender": [64]
  }, [[0, "snkContentCardChanged", "onContentCardChanged"]]]);
SnkDetailView.REGEX_FORM_ID = /__FORM:[^:]+/g;
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-detail-view", "snk-actions-button", "snk-attach", "snk-configurator", "snk-data-exporter", "snk-data-unit", "snk-default-filter", "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-summary", "snk-form-view", "snk-grid", "snk-grid-config", "snk-layout-form-config", "snk-personalized-filter", "snk-select-box", "snk-simple-bar", "snk-simple-crud", "snk-simple-form-config", "snk-taskbar", "snk-view-representation", "taskbar-actions-button", "taskbar-split-button"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-detail-view":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkDetailView);
      }
      break;
    case "snk-actions-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$y();
      }
      break;
    case "snk-attach":
      if (!customElements.get(tagName)) {
        defineCustomElement$x();
      }
      break;
    case "snk-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$w();
      }
      break;
    case "snk-data-exporter":
      if (!customElements.get(tagName)) {
        defineCustomElement$v();
      }
      break;
    case "snk-data-unit":
      if (!customElements.get(tagName)) {
        defineCustomElement$u();
      }
      break;
    case "snk-default-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$t();
      }
      break;
    case "snk-exporter-email-sender":
      if (!customElements.get(tagName)) {
        defineCustomElement$s();
      }
      break;
    case "snk-expression-group":
      if (!customElements.get(tagName)) {
        defineCustomElement$r();
      }
      break;
    case "snk-expression-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$q();
      }
      break;
    case "snk-filter-advanced-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$p();
      }
      break;
    case "snk-filter-assistent-mode":
      if (!customElements.get(tagName)) {
        defineCustomElement$o();
      }
      break;
    case "snk-filter-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$n();
      }
      break;
    case "snk-filter-detail":
      if (!customElements.get(tagName)) {
        defineCustomElement$m();
      }
      break;
    case "snk-filter-field-search":
      if (!customElements.get(tagName)) {
        defineCustomElement$l();
      }
      break;
    case "snk-filter-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$k();
      }
      break;
    case "snk-filter-modal":
      if (!customElements.get(tagName)) {
        defineCustomElement$j();
      }
      break;
    case "snk-filter-modal-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$i();
      }
      break;
    case "snk-filter-param-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$h();
      }
      break;
    case "snk-form-summary":
      if (!customElements.get(tagName)) {
        defineCustomElement$f();
      }
      break;
    case "snk-form-view":
      if (!customElements.get(tagName)) {
        defineCustomElement$e();
      }
      break;
    case "snk-grid":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "snk-grid-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "snk-layout-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "snk-personalized-filter":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "snk-select-box":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "snk-simple-bar":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "snk-simple-crud":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "snk-simple-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "snk-taskbar":
      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;
  } });
}

export { SnkDetailView as S, defineCustomElement as a, SnkGuidesViewer as b, defineCustomElement$1 as d };
