import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { Action, UserInterface, ApplicationContext } from '@sankhyalabs/core';
import { focusOnFieldSerch, SEARCH_FIELD_FULL_WIDTH, FormLayout } from '@sankhyalabs/ezui/dist/collection/utils';
import { DataBinder } from '@sankhyalabs/ezui/dist/collection/utils/form';
import { g as getPKs, d as defineCustomElement$1 } from './snk-image-input2.js';

const snkDynaformFormViewCss = ".sc-snk-dynaform-form-view-h{display:flex;flex-direction:column;width:100%;flex-wrap:wrap;background-color:var(--background--xlight);padding:var(--space--12, 12px);border-radius:var(--border--radius-medium);border:1px solid var(--color--petroleum-100, #C8CCD3);--ez-form-card-summary-field-content-weight:700}ez-form-view.sc-snk-dynaform-form-view{padding:var(--space--6 ,6px) 0;--ez-form-view__item--padding:0}.level-path.sc-snk-dynaform-form-view{color:var(--color--title-primary, #2B3A54);font-weight:var(--text-weight--medium, 400);padding-right:3px}.summary-wrapper.sc-snk-dynaform-form-view{display:flex;overflow:hidden}.summary-header.sc-snk-dynaform-form-view{border-bottom:1px solid var(--color--strokes);margin-bottom:var(--space--medium);padding-bottom:var(--space--medium)}.summary-container.sc-snk-dynaform-form-view{display:flex;flex-direction:column}.summary-container.sc-snk-dynaform-form-view{padding-right:calc(var(--space--extra-large) / 1.5)}.summary-field.sc-snk-dynaform-form-view{min-width:30px;max-width:200px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.summary-field__title.sc-snk-dynaform-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-dynaform-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 SnkDynaformFormView = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.snkContentCardChanged = createEvent(this, "snkContentCardChanged", 7);
    this.snkRequestClearFieldToFocus = createEvent(this, "snkRequestClearFieldToFocus", 7);
    this._customEditors = new Map();
    this._fieldProps = new Map();
    this.dataUnitObserver = async (action) => {
      var _a;
      if (action.type === Action.RECORDS_COPIED) {
        const sourcePK = this.buildSourceRecordPK(action);
        (_a = this.getImageField()) === null || _a === void 0 ? void 0 : _a.forEach(async (field) => {
          var _a;
          (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.setFieldValue(field.name, JSON.stringify(sourcePK));
        });
      }
    };
    this.customUiBuilders = new Map([
      [UserInterface.IMAGE, (_a) => {
          var { name } = _a, props = __rest(_a, ["name"]);
          return h("snk-image-input", Object.assign({ dataUnit: this.dataUnit, maxSize: Infinity, fieldName: name, entityName: this.entityPath }, props));
        }
      ]
    ]);
    this._singleColumn = false;
    this._currentFormLayout = undefined;
    this.fieldSearch = undefined;
    this.label = undefined;
    this.name = undefined;
    this.fields = undefined;
    this.formMetadata = undefined;
    this.dataUnit = undefined;
    this.recordsValidator = undefined;
    this.fieldToFocus = undefined;
    this.customEditors = undefined;
    this.fieldsProps = undefined;
    this.entityPath = undefined;
  }
  async showUp() {
    var _a, _b;
    if (this._formView) {
      (_b = (_a = this._formView).showUp) === null || _b === void 0 ? void 0 : _b.call(_a);
    }
  }
  /**
   * Registra um editor customizado para campos da grade e formulário
   */
  async addCustomEditor(fieldName, customEditor, detailContext) {
    var _a, _b;
    if (this._formView) {
      (_b = (_a = this._formView).addCustomEditor) === null || _b === void 0 ? void 0 : _b.call(_a, fieldName, customEditor, detailContext);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, { customEditor, detailContext: detailContext !== null && detailContext !== void 0 ? 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-dynaform-form-view.
   */
  async showSearchField() {
    if (!this._headerContainer || !this._ezPopoverFieldColumn)
      return;
    const container = this._headerContainer.getBoundingClientRect();
    if (this.fieldSearch) {
      await focusOnFieldSerch(this.fieldSearch);
      this._ezPopoverFieldColumn.showUnder(this._headerContainer, { horizontalGap: container.width - (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);
    }
  }
  bindFields(fields) {
    var _a;
    if (this._dataBinder == undefined && this.dataUnit != undefined) {
      this._dataBinder = new DataBinder(this.dataUnit);
    }
    if (this._dataBinder && this.dataUnit && this.formMetadata) {
      this._dataBinder.bind(fields, (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.dataUnitId, this.formMetadata, this.recordsValidator);
    }
  }
  disconnectedCallback() {
    if (this._dataBinder != undefined) {
      this._dataBinder.onDisconnectedCallback();
    }
    if (this.dataUnit) {
      this.dataUnit.unsubscribe(this.dataUnitObserver);
    }
  }
  componentDidLoad() {
    if (this.customEditors) {
      this.observePropsCustomEditor(this.customEditors);
    }
    if (this.fieldsProps) {
      this.observeFieldsProps(this.fieldsProps);
    }
    this.initLayoutFormConfig();
  }
  async initLayoutFormConfig() {
    const _application = 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) === FormLayout.CASCADE;
  }
  registerNotifyListeners(layoutFormConfig) {
    var _a;
    if (!layoutFormConfig)
      return;
    (_a = layoutFormConfig.onConfigChange) === null || _a === void 0 ? void 0 : _a.call(layoutFormConfig, (config) => {
      this._singleColumn = (config === FormLayout.CASCADE);
    });
  }
  componentDidRender() {
    var _a;
    this.setCustomEditors();
    this.setFieldProps();
    if (!this.fieldToFocus) {
      return;
    }
    if (!((_a = this.fields) === null || _a === void 0 ? void 0 : _a.some(item => item.name === this.fieldToFocus))) {
      return;
    }
    requestAnimationFrame(() => {
      var _a, _b;
      (_a = this._dataBinder) === null || _a === void 0 ? void 0 : _a.setFocus(this.fieldToFocus);
      (_b = this.snkRequestClearFieldToFocus) === null || _b === void 0 ? void 0 : _b.emit();
    });
  }
  setCustomEditors() {
    var _a, _b;
    if (!this._formView) {
      return;
    }
    for (const [fieldName, customEditorProps] of this._customEditors) {
      (_b = (_a = this._formView).addCustomEditor) === null || _b === void 0 ? void 0 : _b.call(_a, fieldName, customEditorProps.customEditor, customEditorProps.detailContext);
      this._customEditors.delete(fieldName);
    }
  }
  setFieldProps() {
    if (!this._formView) {
      return;
    }
    for (const [fieldName, propsToChange] of this._fieldProps) {
      propsToChange.forEach(prop => {
        var _a, _b;
        (_b = (_a = this._formView).setFieldProp) === null || _b === void 0 ? void 0 : _b.call(_a, fieldName, prop.propName, prop.value);
        this._fieldProps.delete(fieldName);
      });
    }
  }
  buildSourceRecordPK(action) {
    var _a, _b, _c;
    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__"];
    if (!this.dataUnit) {
      return {};
    }
    const pks = (_b = getPKs(this.dataUnit)) !== null && _b !== void 0 ? _b : {};
    const pkFields = Object.keys(pks);
    const filteredSourceRecord = {};
    for (const pkField of pkFields) {
      filteredSourceRecord[pkField] = (_c = sourceRecord[pkField]) === null || _c === void 0 ? void 0 : _c.value;
    }
    return filteredSourceRecord;
  }
  getImageField() {
    var _a;
    return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.metadata.fields.filter(field => field.userInterface === UserInterface.IMAGE);
  }
  render() {
    return (h(Host, null, h("slot", null), h("ez-form-view", { ref: (ref) => this._formView = ref, fields: this.fields, onEzContentReady: evt => this.bindFields(evt.detail), singleColumn: this._singleColumn, customUiBuilders: this.customUiBuilders, formLayout: this._currentFormLayout }), this.fieldSearch && h("ez-popover", { ref: elem => (this._ezPopoverFieldColumn = elem), overlayType: "none" }, this.fieldSearch)));
  }
  static get watchers() { return {
    "customEditors": ["observePropsCustomEditor"],
    "fieldsProps": ["observeFieldsProps"],
    "dataUnit": ["observeDataUnit"]
  }; }
  static get style() { return snkDynaformFormViewCss; }
}, [6, "snk-dynaform-form-view", {
    "fieldSearch": [16],
    "label": [1],
    "name": [1],
    "fields": [16],
    "formMetadata": [8, "form-metadata"],
    "dataUnit": [16],
    "recordsValidator": [16],
    "fieldToFocus": [1, "field-to-focus"],
    "customEditors": [16],
    "fieldsProps": [16],
    "entityPath": [1, "entity-path"],
    "_singleColumn": [32],
    "_currentFormLayout": [32],
    "showUp": [64],
    "addCustomEditor": [64],
    "setFieldProp": [64],
    "showSearchField": [64]
  }]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-dynaform-form-view", "snk-image-input"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-dynaform-form-view":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkDynaformFormView);
      }
      break;
    case "snk-image-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}

export { SnkDynaformFormView as S, defineCustomElement as d };
