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