import { r as registerInstance, e as createEvent, i as forceUpdate, h, f as Host, g as getElement } from './index-e9c7ceaa.js';
import { Action, StringUtils, KeyboardManager } from '@sankhyalabs/core';
import { S as SnkFormConfigManager } from './SnkFormConfigManager-28deba35.js';
import { FormMetadata, buildFormMetadata } from '@sankhyalabs/ezui/dist/collection/utils/form';
import { S as SnkMessageBuilder } from './DataFetcher-955ee53e.js';
import './ISave-c8bf12c4.js';
import { P as PresentationMode } from './index-b40568ff.js';
import '@sankhyalabs/ezui/dist/collection/utils/constants';
import '@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata';
import './dataunit-fetcher-6cacb959.js';
import './filter-item-type.enum-d45e026f.js';
import './form-config-fetcher-baa89098.js';
import { V as VIEW_MODE } from './constants-7b422de0.js';
import { T as TaskbarElement } from './taskbar-elements-b3c5a3ce.js';
import { S as SnkGuidesViewer } from './snk-guides-viewer-2fa1b17e.js';
import { buildFieldSearch, SHORTCUT_SEARCH_FIELD } from '@sankhyalabs/ezui/dist/collection/utils';
import './ConfigStorage-4eee53da.js';
import './PrintUtils-3e4ff0f5.js';
import '@sankhyalabs/ezui/dist/collection/components/ez-grid/utils';
import '@sankhyalabs/core/dist/utils/SortingUtils';
import './ResourceIDUtils-a114189a.js';
import './index-c961465b.js';
import './taskbar-processor-3436124c.js';
import '@sankhyalabs/core/dist/dataunit/DataUnit';

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 = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    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 getElement(this); }
  static get watchers() { return {
    "dataUnit": ["observeDataUnit"],
    "dataState": ["observerDataState"],
    "customEditors": ["observerPropsCustomEditor"],
    "customRenders": ["observeCustomRenders"]
  }; }
};
SnkDetailView.REGEX_FORM_ID = /__FORM:[^:]+/g;
SnkDetailView.style = snkDetailViewCss;

export { SnkDetailView as snk_detail_view };
