'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-1894343a.js');
const core = require('@sankhyalabs/core');
const SnkFormConfigManager = require('./SnkFormConfigManager-18e527c4.js');
const form = require('@sankhyalabs/ezui/dist/collection/utils/form');
const DataFetcher = require('./DataFetcher-b3a8075d.js');
require('./ISave-4674c283.js');
const index$1 = require('./index-e3e39724.js');
require('@sankhyalabs/ezui/dist/collection/utils/constants');
require('@sankhyalabs/core/dist/dataunit/metadata/UnitMetadata');
require('./dataunit-fetcher-bcbc38c0.js');
require('./filter-item-type.enum-a7ffdaa6.js');
require('./form-config-fetcher-858d6407.js');
const constants = require('./constants-6d82e405.js');
const taskbarElements = require('./taskbar-elements-80eddec8.js');
const snkGuidesViewer = require('./snk-guides-viewer-b37019ad.js');
const utils = require('@sankhyalabs/ezui/dist/collection/utils');
require('./ConfigStorage-389e982d.js');
require('./PrintUtils-bcaeb82f.js');
require('@sankhyalabs/ezui/dist/collection/components/ez-grid/utils');
require('@sankhyalabs/core/dist/utils/SortingUtils');
require('./ResourceIDUtils-5ff86aa7.js');
require('./index-f0fe7e6e.js');

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 DataFetcher.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 = form.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.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% - 56px);--snk-grid__header-padding:var(--space--4, 4px);--snk-grid-padding:var(--space--8, 8px);--snk-grid-box-shadow:unset}";

const SnkDetailView = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.snkDetailGuidesChange = index.createEvent(this, "snkDetailGuidesChange", 7);
    this.snkSwitchGuide = index.createEvent(this, "snkSwitchGuide", 7);
    this.formItemsReady = index.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 = index$1.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(constants.VIEW_MODE.FORM);
      }, 0);
    }
    if (closeInsertion) {
      this.changeViewMode(constants.VIEW_MODE.GRID);
    }
    const disabledButtons = [];
    if (!this.dataState.hasPrevious) {
      disabledButtons.push(taskbarElements.TaskbarElement.PREVIOUS);
    }
    if (!this.dataState.hasNext) {
      disabledButtons.push(taskbarElements.TaskbarElement.NEXT);
    }
    if (this.dataState.insertionMode) {
      disabledButtons.push(taskbarElements.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.SnkGuidesViewer.updateContentCard(evt.detail.formName, evt.detail.cardConfig, evt.detail.propertyChanged, this.formConfigManager).then(() => index.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 = form.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) {
    if (mode === constants.VIEW_MODE.GRID) {
      this.dataUnit.isMultipleEdition = false;
    }
    const guideId = mode === constants.VIEW_MODE.GRID ? this.stripFormPattern(this.branchGuide.id) : this.getFormGuideId();
    if (guideId) {
      this.snkSwitchGuide.emit(guideId);
    }
  }
  executeActionHandler(evt) {
    if (evt.detail === taskbarElements.TaskbarElement.GRID_MODE) {
      this.emitSwitchEvent(constants.VIEW_MODE.GRID);
      evt.stopPropagation();
    }
    if (evt.detail === taskbarElements.TaskbarElement.UPDATE_MULTIPLE) {
      this.dataUnit.isMultipleEdition = true;
      this.emitSwitchEvent(constants.VIEW_MODE.FORM);
      evt.stopPropagation();
    }
    if (evt.detail === taskbarElements.TaskbarElement.FORM_MODE || evt.detail === taskbarElements.TaskbarElement.UPDATE) {
      this.emitSwitchEvent(constants.VIEW_MODE.FORM);
      evt.stopPropagation();
    }
    if (evt.detail === taskbarElements.TaskbarElement.ATTACH) {
      this._snkAttach.open();
      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.SnkFormConfigManager(this._configName, this.resourceID, () => this.loadMetadata(), this.dataUnit);
    this.formConfigManager.loadConfig();
    if (this.messagesBuilder == undefined) {
      this.messagesBuilder = new DataFetcher.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 === core.Action.FIELD_INVALIDATED) {
      this.addErrorBadgeToBranchGuide();
    }
    else if (action.type === core.Action.DATA_LOADED) {
      this.handleDataLoaded();
    }
  }
  handleDataLoaded() {
    var _a;
    if (!((_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getSelectedRecord())) {
      this.dataUnit.selectFirst();
    }
  }
  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: core.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 = utils.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 core.KeyboardManager({ propagate: false, element: this._element });
    this._keyboardManager.bind(utils.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 (index.h(index.Host, null, index.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 === constants.VIEW_MODE.GRID, messagesBuilder: this.messagesBuilder, configName: this._configName }, index.h("ez-view-stack", { ref: (ref) => this.updateViewStack(ref) }, index.h("stack-item", null, index.h("div", { class: "ez-box ez-box--shadow grid-container" }, index.h("div", { class: "ez-title--primary ez-size-width--full ez-padding--large detail-header" }, index.h("div", { class: "ez-flex ez-text ez-text--bold ez-flex--justify-start ez-flex--align-items-center" }, this._levelPath ? index.h("span", { class: "level-path" }, this._levelPath + " /") : undefined, this.label)), index.h("snk-grid", { class: "ez-size-width--full", ref: (ref) => this._snkGrid = ref, configName: this._configName, messagesBuilder: this.messagesBuilder, onGridDoubleClick: () => this.emitSwitchEvent(constants.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, enableGridInsert: true, autoLoad: true, multipleEditionEnabled: true, multipleSelection: true }))), index.h("stack-item", null, index.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, entityPath: this.entityName }, index.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() }, index.h("slot", { name: "DETAIL_TASKBAR_CUSTOM_ELEMENTS" }))))), index.h("snk-attach", { ref: (ref) => this._snkAttach = ref, registerKey: this.attachmentRegisterKey, messagesBuilder: this.messagesBuilder, entityName: this.entityName }))));
  }
  get _element() { return index.getElement(this); }
  static get watchers() { return {
    "dataUnit": ["observeDataUnit"],
    "dataState": ["observerDataState"],
    "customEditors": ["observerPropsCustomEditor"],
    "customRenders": ["observeCustomRenders"]
  }; }
};
SnkDetailView.REGEX_FORM_ID = /__FORM:[^:]+/g;
SnkDetailView.style = snkDetailViewCss;

exports.snk_detail_view = SnkDetailView;
