'use strict';

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

const index = require('./index-17105557.js');
const core = require('@sankhyalabs/core');
const form = require('@sankhyalabs/ezui/dist/collection/utils/form');
const utils = require('@sankhyalabs/ezui/dist/collection/utils');

const snkFormViewCss = ".sc-snk-form-view-h{display:flex;width:100%;--ez-form-card-summary-field-content-weight:700}.level-path.sc-snk-form-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.summary-wrapper.sc-snk-form-view{display:flex;overflow:hidden}.summary-header.sc-snk-form-view{border-bottom:1px solid var(--color--strokes);margin-bottom:var(--space--medium);padding-bottom:var(--space--medium)}.summary-container.sc-snk-form-view{display:flex;flex-direction:column}.summary-container.sc-snk-form-view{padding-right:calc(var(--space--extra-large) / 1.5)}.summary-field.sc-snk-form-view{min-width:30px;max-width:200px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.summary-field__title.sc-snk-form-view{color:var(--text--primary, #626e82);font-size:var(--title--small);white-space:nowrap;font-weight:var(--text-weight--medium)}.summary-field__content.sc-snk-form-view{color:var(--title--primary, #2b3a54);font-size:var(--text--large);font-weight:var(--ez-form-card-summary-field-content-weight)}";

const SnkFormView = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.snkContentCardChanged = index.createEvent(this, "snkContentCardChanged", 7);
    this.snkRequestClearFieldToFocus = index.createEvent(this, "snkRequestClearFieldToFocus", 7);
    this.formItemsReady = index.createEvent(this, "formItemsReady", 7);
    this._customEditors = new Map();
    this._fieldProps = new Map();
    this._singleColumn = false;
    this.levelPath = undefined;
    this.fieldSearch = undefined;
    this.label = undefined;
    this.name = undefined;
    this.fields = undefined;
    this.formMetadata = undefined;
    this.dataUnit = undefined;
    this.contracted = undefined;
    this.fixed = false;
    this.summaryFields = undefined;
    this.canExpand = true;
    this.canFix = true;
    this.recordsValidator = undefined;
    this.fieldToFocus = undefined;
    this.customEditors = undefined;
    this.fieldsProps = undefined;
  }
  async showUp() {
    if (this._formView) {
      this._formView.showUp();
    }
  }
  /**
   * Registra um editor customizado para campos da grade e formulário
   */
  async addCustomEditor(fieldName, customEditor, detailContext) {
    if (this._formView) {
      this._formView.addCustomEditor(fieldName, customEditor, detailContext);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, { customEditor, detailContext });
    this._customEditors = newCustomEditors;
  }
  /**
   * Altera/adiciona uma propriedade nos metadados do campo.
   */
  async setFieldProp(fieldName, propName, value) {
    const props = this._fieldProps.get(fieldName) || [];
    this._fieldProps.set(fieldName, [...props, { propName, value }]);
  }
  /**
   * Exibe a busca de campos ancorada ao container de cabeçalho do snk-form-view.
   */
  async showSearchField() {
    if (!this._headerContainer || !this._ezPopoverFieldColumn)
      return;
    const container = this._headerContainer.getBoundingClientRect();
    await utils.focusOnFieldSerch(this.fieldSearch);
    this._ezPopoverFieldColumn.showUnder(this._headerContainer, { horizontalGap: container.width - (utils.SEARCH_FIELD_FULL_WIDTH), verticalGap: container.height * -1 });
  }
  observePropsCustomEditor(newValue) {
    for (const fieldName in newValue) {
      this.addCustomEditor(fieldName, newValue[fieldName]);
    }
  }
  async observeFieldsProps(newValue) {
    for (const field in newValue) {
      const fieldProps = newValue[field];
      const propNames = Object.keys(fieldProps);
      for (const propName of propNames) {
        await this.setFieldProp(field, propName, fieldProps[propName]);
      }
    }
  }
  changeFix() {
    this.fixed = !this.fixed;
    this.emitEvent("fixed");
  }
  changeContracted() {
    this.contracted = !this.contracted;
    this.emitEvent("presentation");
  }
  emitEvent(propertyChanged) {
    this.snkContentCardChanged.emit({
      formName: this.name,
      cardConfig: {
        fixed: this.fixed,
        presentation: this.contracted ? "CONTRACTED" : "EXPANDED"
      },
      propertyChanged
    });
  }
  getCardSummary() {
    const summary = {};
    this.getSummaryFields().forEach(({ field, label }) => {
      var _a;
      const value = this.dataUnit.getFormattedValue(field);
      if (value !== "") {
        if (label == undefined) {
          label = (_a = this.dataUnit.getField(field)) === null || _a === void 0 ? void 0 : _a.label;
        }
        summary[label] = value;
      }
    });
    return summary;
  }
  getSummaryFields() {
    if (this.summaryFields == undefined) {
      return this.fields.map(field => {
        const descriptor = this.dataUnit.getField(field.name);
        return { field: field.name, label: field.label || (descriptor === null || descriptor === void 0 ? void 0 : descriptor.label) };
      });
    }
    return this.summaryFields;
  }
  bindFields(fields) {
    if (this._dataBinder == undefined && this.dataUnit != undefined) {
      this._dataBinder = new form.DataBinder(this.dataUnit);
    }
    if (this._dataBinder) {
      this._dataBinder.bind(fields, this.dataUnit.dataUnitId, this.formMetadata, this.recordsValidator);
    }
  }
  handleFormItemsReady(event) {
    event.stopPropagation();
    this.formItemsReady.emit(Object.assign(Object.assign({}, event.detail), { formId: this.name }));
  }
  disconnectedCallback() {
    if (this._dataBinder != undefined) {
      this._dataBinder.onDisconnectedCallback();
    }
  }
  componentDidLoad() {
    this.observePropsCustomEditor(this.customEditors);
    this.observeFieldsProps(this.fieldsProps);
    this.initLayoutFormConfig();
  }
  async initLayoutFormConfig() {
    const _application = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
    const layoutFormConfig = await (_application === null || _application === void 0 ? void 0 : _application.getLayoutFormConfig());
    if (layoutFormConfig) {
      this.setSingleColumn(layoutFormConfig);
      this.registerNotifyListeners(layoutFormConfig);
    }
  }
  setSingleColumn(layoutFormConfig) {
    this._singleColumn = (layoutFormConfig === null || layoutFormConfig === void 0 ? void 0 : layoutFormConfig.config) === utils.FormLayout.CASCADE;
  }
  registerNotifyListeners(layoutFormConfig) {
    if (!layoutFormConfig)
      return;
    layoutFormConfig.onConfigChange((config) => {
      this._singleColumn = (config === utils.FormLayout.CASCADE);
    });
  }
  componentDidRender() {
    this.setCustomEditors();
    this.setFieldProps();
    if (this.fieldToFocus == undefined) {
      return;
    }
    if (!this.fields.some(item => item.name === this.fieldToFocus)) {
      return;
    }
    requestAnimationFrame(() => {
      this._dataBinder.setFocus(this.fieldToFocus);
      this.snkRequestClearFieldToFocus.emit();
    });
  }
  setCustomEditors() {
    if (!this._formView) {
      return;
    }
    for (const [fieldName, customEditorProps] of this._customEditors) {
      this._formView.addCustomEditor(fieldName, customEditorProps.customEditor, customEditorProps.detailContext);
      this._customEditors.delete(fieldName);
    }
  }
  setFieldProps() {
    if (!this._formView) {
      return;
    }
    for (const [fieldName, propsToChange] of this._fieldProps) {
      propsToChange.forEach(prop => {
        this._formView.setFieldProp(fieldName, prop.propName, prop.value);
        this._fieldProps.delete(fieldName);
      });
    }
  }
  render() {
    return (index.h(index.Host, { class: "ez-box__container" }, index.h("div", { class: "summary-header ez-flex ez-size-width--full", ref: ref => this._headerContainer = ref }, index.h("div", { class: "ez-flex ez-text ez-title--primary ez-text--bold ez-flex--justify-start ez-flex--align-items-center ez-col--sd-9" }, this.levelPath ? index.h("span", { class: "level-path" }, this.levelPath + " /") : undefined, this.label), index.h("div", { class: "ez-flex ez-flex--justify-end ez-col--sd-3" }, this.canFix &&
      index.h("ez-button", { class: "ez-padding-left--medium", mode: "icon", size: "small", iconName: this.fixed ? "un-pin" : "push-pin", "data-element-id": core.ElementIDUtils.getInternalIDInfo("toggleFixed_ezFormCard"), onClick: () => this.changeFix(), title: this.fixed ? "Desafixar" : "Fixar" }), this.canExpand &&
      index.h("ez-button", { class: "ez-padding-left--medium", mode: "icon", size: "small", iconName: this.contracted ? "chevron-down" : "chevron-up", "data-element-id": core.ElementIDUtils.getInternalIDInfo("toggleExpand_ezFormCard"), onClick: () => this.changeContracted(), title: this.contracted ? "Expandir" : "Resumir" }))), index.h("slot", null), this.contracted
      ?
        index.h("snk-form-summary", { summary: this.getCardSummary() })
      :
        index.h("ez-form-view", { ref: ref => this._formView = ref, fields: this.fields, onEzContentReady: evt => this.bindFields(evt.detail), onFormItemsReady: (event) => this.handleFormItemsReady(event), singleColumn: this._singleColumn }), this.fieldSearch && index.h("ez-popover", { ref: elem => (this._ezPopoverFieldColumn = elem), overlayType: "none" }, this.fieldSearch)));
  }
  static get watchers() { return {
    "customEditors": ["observePropsCustomEditor"],
    "fieldsProps": ["observeFieldsProps"]
  }; }
};
SnkFormView.style = snkFormViewCss;

exports.snk_form_view = SnkFormView;
