import { Action as DUAction, ElementIDUtils, KeyboardManager, StringUtils, ObjectUtils } from '@sankhyalabs/core';
import { Fragment, h } from '@stencil/core';
import { SnkFormConfigManager } from '../../snk-form-config/SnkFormConfigManager';
import { buildFormMetadata, FormMetadata } from '@sankhyalabs/ezui/dist/collection/utils/form';
import TaskbarProcessor from '../../snk-taskbar/processor/taskbar-processor';
import { TaskbarElement } from '../../snk-taskbar/elements/taskbar-elements';
import { VIEW_MODE } from '../../../lib/utils/constants';
import { PresentationMode } from '../../../lib';
import { SelectionMode } from '@sankhyalabs/core/dist/dataunit/DataUnit';
import { buildFieldSearch, SHORTCUT_SEARCH_FIELD } from '@sankhyalabs/ezui/dist/collection/utils';
const FORM_NAME_PREFIX = "__FORM:";
export class SnkGuidesViewer {
  constructor() {
    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 DUAction.EDITION_CANCELED:
      case DUAction.DATA_SAVED:
        if (this.dataUnit.isMultipleEdition) {
          this.exitViewer();
          this.dataUnit.isMultipleEdition = false;
        }
        break;
      case DUAction.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 DUAction.METADATA_LOADED:
      case DUAction.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 })));
  }
  static get is() { return "snk-guides-viewer"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-guides-viewer.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-guides-viewer.css"]
    };
  }
  static get properties() {
    return {
      "dataUnit": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "DataUnit",
          "resolved": "DataUnit",
          "references": {
            "DataUnit": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Inst\u00E2ncia do DataUnit master."
        }
      },
      "dataState": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "DataState",
          "resolved": "DataState",
          "references": {
            "DataState": {
              "location": "import",
              "path": "../../snk-data-unit/snk-data-unit"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Representa o estado do dataUnit master."
        }
      },
      "configName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Nome usado para guardar/recuperar as configura\u00E7\u00F5es do formul\u00E1rio."
        },
        "attribute": "config-name",
        "reflect": false
      },
      "entityPath": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Determina todo o caminho de entidades."
        },
        "attribute": "entity-path",
        "reflect": false
      },
      "actionsList": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Array<Action>",
          "resolved": "Action[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "Action": {
              "location": "import",
              "path": "../../snk-taskbar/snk-taskbar"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "A\u00E7\u00F5es a serem colocadas no bot\u00E3o \"Mais op\u00E7\u00F5es\" do componente snk-taskbar."
        }
      },
      "recordsValidator": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "IRecordValidator",
          "resolved": "IRecordValidator",
          "references": {
            "IRecordValidator": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils/form/interfaces"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Validador respons\u00E1vel por checar a integridade das informa\u00E7\u00F5es do registro."
        }
      },
      "masterFormConfig": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "IFormConfig",
          "resolved": "IFormConfig",
          "references": {
            "IFormConfig": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils/form/interfaces"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Configura\u00E7\u00E3o do formul\u00E1rio master."
        }
      },
      "selectedGuide": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "IGuideItem",
          "resolved": "IGuideItem",
          "references": {
            "IGuideItem": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/components/ez-guide-navigator/interfaces"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Guia selecionada."
        }
      },
      "taskbarManager": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "TaskbarManager",
          "resolved": "TaskbarManager",
          "references": {
            "TaskbarManager": {
              "location": "import",
              "path": "../../snk-taskbar/snk-taskbar"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Gerenciador das barras de tarefas. \u00C9 poss\u00EDvel determinar bot\u00F5es espec\u00EDficos\nou mesmo gerenciar o estado dos bot\u00F5es."
        }
      },
      "messagesBuilder": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Respons\u00E1vel por flexibilizar e padronizar o uso de mensagens nos blocos de constru\u00E7\u00E3o."
        }
      },
      "canEdit": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se a edi\u00E7\u00E3o est\u00E1 habilitada na grid."
        },
        "attribute": "can-edit",
        "reflect": false,
        "defaultValue": "true"
      },
      "presentationMode": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "PresentationMode",
          "resolved": "PresentationMode.PRIMARY | PresentationMode.SECONDARY | PresentationMode.SINGLE_TASKBAR",
          "references": {
            "PresentationMode": {
              "location": "import",
              "path": "../../../lib"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Altera o modo de apresenta\u00E7\u00E3o dos bot\u00F5es do snk-taskbar."
        },
        "attribute": "presentation-mode",
        "reflect": false
      },
      "resourceID": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Identificador de recursos como configura\u00E7\u00F5es e acesso."
        },
        "attribute": "resource-i-d",
        "reflect": false
      },
      "detailTaskbarCustomContainerId": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o identificador do container de elementos customizados da Taskbar da aba de detalhes."
        },
        "attribute": "detail-taskbar-custom-container-id",
        "reflect": false
      },
      "formLegacyConfigName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Chave da configura\u00E7\u00E3o legado do formul\u00E1rio."
        },
        "attribute": "form-legacy-config-name",
        "reflect": false
      },
      "enableGridInsert": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Ativa inser\u00E7\u00E3o de registros no modo grade."
        },
        "attribute": "enable-grid-insert",
        "reflect": false,
        "defaultValue": "false"
      },
      "ignoreReadOnlyFormFields": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Ignora os campos \"somente leitura\" no modo de inser\u00E7\u00E3o."
        },
        "attribute": "ignore-read-only-form-fields",
        "reflect": false
      },
      "getCustomTitle": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "() => string",
          "resolved": "() => string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Fornece  uma fun\u00E7\u00E3o para obter um t\u00EDtulo customizado do formul\u00E1rio."
        }
      }
    };
  }
  static get states() {
    return {
      "_hasToCreateFieldSearch": {},
      "_breadcrumbItems": {},
      "_guides": {},
      "_formEditorConfigManager": {},
      "_formEditorDataUnit": {},
      "_fieldToGetFocus": {},
      "_customEditors": {},
      "_customRenders": {},
      "_fieldsProps": {},
      "_mainForm": {}
    };
  }
  static get events() {
    return [{
        "method": "snkMasterFormConfigChange",
        "name": "snkMasterFormConfigChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando a configura\u00E7\u00E3o do formul\u00E1rio master \u00E9 definida."
        },
        "complexType": {
          "original": "IFormConfig",
          "resolved": "IFormConfig",
          "references": {
            "IFormConfig": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils/form/interfaces"
            }
          }
        }
      }, {
        "method": "exit",
        "name": "exit",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando o bot\u00E3o de voltar \u00E9 acionado."
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }, {
        "method": "actionClick",
        "name": "actionClick",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido sempre que houver click de bot\u00E3o ou a\u00E7\u00E3o."
        },
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        }
      }, {
        "method": "formItemsReady",
        "name": "formItemsReady",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Respons\u00E1vel por notificar quando ocorrer a renderiza\u00E7\u00E3o de itens do formul\u00E1rio."
        },
        "complexType": {
          "original": "Array<HTMLElement>",
          "resolved": "HTMLElement[]",
          "references": {
            "Array": {
              "location": "global"
            },
            "HTMLElement": {
              "location": "global"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "showFormConfig": {
        "complexType": {
          "signature": "(detail?: boolean) => Promise<void>",
          "parameters": [{
              "tags": [{
                  "name": "param",
                  "text": "detail - Define se a configura\u00E7\u00E3o que est\u00E1 sendo carregada \u00E9\nreferente a um form detail."
                }],
              "text": "- Define se a configura\u00E7\u00E3o que est\u00E1 sendo carregada \u00E9\nreferente a um form detail."
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Abre o configurador do formul\u00E1rio",
          "tags": [{
              "name": "param",
              "text": "detail - Define se a configura\u00E7\u00E3o que est\u00E1 sendo carregada \u00E9\nreferente a um form detail."
            }]
        }
      },
      "addCustomEditor": {
        "complexType": {
          "signature": "(fieldName: string, customEditor: ICustomEditor) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomEditor": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Registra um editor customizado para campos da grade e formul\u00E1rio",
          "tags": []
        }
      },
      "addGridCustomRender": {
        "complexType": {
          "signature": "(fieldName: string, customRender: ICustomRender) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "ICustomRender": {
              "location": "import",
              "path": "@sankhyalabs/ezui/dist/types/utils"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Registra um render customizado para colunas da grid.",
          "tags": []
        }
      },
      "setFieldProp": {
        "complexType": {
          "signature": "(fieldName: string, propName: string, value: any) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Altera/adiciona uma propriedade nos metadados do campo.",
          "tags": []
        }
      },
      "setFocus": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Atribui o foco para o componente.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
  static get watchers() {
    return [{
        "propName": "dataUnit",
        "methodName": "observeDataUnit"
      }, {
        "propName": "dataState",
        "methodName": "observeDataState"
      }, {
        "propName": "masterFormConfig",
        "methodName": "observeMasterFormConfig"
      }];
  }
  static get listeners() {
    return [{
        "name": "actionClick",
        "method": "onActionClick",
        "target": undefined,
        "capture": true,
        "passive": false
      }, {
        "name": "snkContentCardChanged",
        "method": "onContentCardChanged",
        "target": undefined,
        "capture": false,
        "passive": false
      }];
  }
}
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 = {}));
