'use strict';

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

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

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)}";

var __rest = (undefined && undefined.__rest) || function (s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
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.dataUnitObserver = async (action) => {
      if (action.type === core.Action.RECORDS_COPIED) {
        const sourcePK = this.buildSourceRecordPK(action);
        this.getImageField().forEach(async (field) => {
          this.dataUnit.setFieldValue(field.name, JSON.stringify(sourcePK));
        });
      }
    };
    this.customUiBuilders = new Map([
      [core.UserInterface.IMAGE, (_a) => {
          var { name } = _a, props = __rest(_a, ["name"]);
          return index.h("snk-image-input", Object.assign({ dataUnit: this.dataUnit, maxSize: Infinity, fieldName: name, entityName: this.entityPath }, props));
        }
      ]
    ]);
    this._singleColumn = false;
    this._currentFormLayout = undefined;
    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;
    this.entityPath = 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]);
      }
    }
  }
  async observeDataUnit(newValue, oldValue) {
    if (newValue !== oldValue && newValue) {
      newValue.subscribe(this.dataUnitObserver);
    }
  }
  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();
    }
    if (this.dataUnit) {
      this.dataUnit.unsubscribe(this.dataUnitObserver);
    }
  }
  async componentWillLoad() {
    await this.initLayoutFormConfig();
  }
  componentDidLoad() {
    this.observePropsCustomEditor(this.customEditors);
    this.observeFieldsProps(this.fieldsProps);
  }
  async initLayoutFormConfig() {
    var _a;
    if (!this._application) {
      this._application = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
    }
    const layoutFormConfig = await ((_a = this._application) === null || _a === void 0 ? void 0 : _a.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 || (layoutFormConfig === null || layoutFormConfig === void 0 ? void 0 : layoutFormConfig.config) === utils.FormLayout.CLASSIC_CASCADE;
    this._currentFormLayout = layoutFormConfig === null || layoutFormConfig === void 0 ? void 0 : layoutFormConfig.config;
  }
  registerNotifyListeners(layoutFormConfig) {
    if (!layoutFormConfig)
      return;
    layoutFormConfig.onConfigChange((config) => {
      this._singleColumn = (config === utils.FormLayout.CASCADE || config === utils.FormLayout.CLASSIC_CASCADE);
      this._currentFormLayout = config;
    });
  }
  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);
      });
    }
  }
  buildSourceRecordPK(action) {
    var _a, _b;
    const currentRecord = ((_a = action.payload) === null || _a === void 0 ? void 0 : _a[0]) || {};
    const sourceBase64 = currentRecord["__record__source__id__"];
    const sourceRecord = JSON.parse(atob(sourceBase64 || ''));
    delete sourceRecord["__DATA_UNIT_NAME__"];
    const pkFields = Object.keys(ImageUtils.getPKs(this.dataUnit));
    const filteredSourceRecord = {};
    for (const pkField of pkFields) {
      filteredSourceRecord[pkField] = (_b = sourceRecord[pkField]) === null || _b === void 0 ? void 0 : _b.value;
    }
    return filteredSourceRecord;
  }
  getImageField() {
    return this.dataUnit.metadata.fields.filter(field => field.userInterface === core.UserInterface.IMAGE);
  }
  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, customUiBuilders: this.customUiBuilders, formLayout: this._currentFormLayout }), this.fieldSearch && index.h("ez-popover", { ref: elem => (this._ezPopoverFieldColumn = elem), overlayType: "none" }, this.fieldSearch)));
  }
  static get watchers() { return {
    "customEditors": ["observePropsCustomEditor"],
    "fieldsProps": ["observeFieldsProps"],
    "dataUnit": ["observeDataUnit"]
  }; }
};
SnkFormView.style = snkFormViewCss;

exports.snk_form_view = SnkFormView;
