import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { ElementIDUtils } from '@sankhyalabs/core';
import { S as SnkFormConfigManager } from './SnkFormConfigManager.js';
import { R as ResourceIDUtils } from './ResourceIDUtils.js';
import { d as defineCustomElement$9 } from './config-header2.js';
import { d as defineCustomElement$8 } from './configs-button2.js';
import { d as defineCustomElement$7 } from './field-config2.js';
import { d as defineCustomElement$6 } from './field-item2.js';
import { d as defineCustomElement$5 } from './fields-layout2.js';
import { d as defineCustomElement$4 } from './fields-selector2.js';
import { d as defineCustomElement$3 } from './guides-configurator2.js';
import { d as defineCustomElement$2 } from './snk-form-config2.js';

const snkFormCss = ".sc-snk-form-h{--snk-form__header--min-height:94px;display:block}.snk-form__form--hidden.sc-snk-form{display:none}";

const SnkForm$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.exit = createEvent(this, "exit", 7);
    this.actionClick = createEvent(this, "actionClick", 7);
    this.formItemsReady = createEvent(this, "formItemsReady", 7);
    this._customEditors = new Map();
    this._dataUnit = undefined;
    this._dataState = undefined;
    this._showFormConfig = false;
    this._configManager = undefined;
    this.configName = undefined;
    this.recordsValidator = undefined;
    this.messagesBuilder = undefined;
    this.formLegacyConfigName = undefined;
    this.resourceID = undefined;
  }
  /**
   * Exibe a janela de configurações do formulário.
   * @async
   * @returns {Promise<void>}
   */
  async showConfig() {
    this._showFormConfig = true;
  }
  /**
   * Fecha a janela de configurações do formulário.
   * @async
   * @returns {Promise<void>}
   */
  async hideConfig() {
    this._showFormConfig = false;
  }
  /**
   * Registra um editor customizado para campos do formulário.
   * @async
   * @param {string} fieldName - Nome do campo.
   * @param {ICustomEditor} customEditor - Editor customizado.
   * @returns {Promise<void>}
   */
  async addCustomEditor(fieldName, customEditor) {
    if (this._form) {
      this._form.addCustomEditor(fieldName, customEditor);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, customEditor);
    this._customEditors = newCustomEditors;
  }
  /**
   * Altera/adiciona uma propriedade nos metadados do campo.
   * @async
   * @param {string} fieldName - Nome do campo.
   * @param {string} propName - Nome da propriedade.
   * @param {any} value - Valor da propriedade.
   * @returns {Promise<void>}
   */
  async setFieldProp(fieldName, propName, value) {
    await this._form.setFieldProp(fieldName, propName, value);
  }
  /**
   * Valida o formulário.
   * @async
   * @returns {Promise<void>}
   * @description
   * Este método executa a validação do formulário, verificando se todos os campos estão
   * preenchidos corretamente de acordo com as regras definidas.
   * Se a validação falhar, uma exceção será lançada com os detalhes dos erros encontrados.
   * Caso contrário, o método será resolvido sem erros.
   */
  async validate() {
    await this._form.validate();
  }
  closeConfig() {
    this.hideConfig();
  }
  dataunitReady() {
    const dataInfo = { dataUnit: this._dataUnit };
    ElementIDUtils.addIDInfo(this._element, null, dataInfo);
  }
  setCustomEditors() {
    if (!this._form) {
      return;
    }
    for (const [fieldName, customEditor] of this._customEditors) {
      this._form.addCustomEditor(fieldName, customEditor);
      this._customEditors.delete(fieldName);
    }
  }
  async componentDidRender() {
    this.setCustomEditors();
  }
  async componentWillLoad() {
    let parent = this._element.parentElement;
    while (parent) {
      if (parent.tagName.toUpperCase() === "SNK-DATA-UNIT") {
        this._snkDataUnit = parent;
        this._dataUnit = this._snkDataUnit.dataUnit;
        this._dataState = this._snkDataUnit.dataState;
        if (this._dataUnit) {
          this.dataunitReady();
        }
        else {
          this._snkDataUnit.addEventListener("dataUnitReady", (evt) => {
            this._dataUnit = evt.detail;
          });
        }
        this._snkDataUnit.addEventListener("dataStateChange", this.handleDataStateChange.bind(this));
        break;
      }
      parent = parent.parentElement;
    }
    if (this.resourceID == undefined) {
      this.resourceID = await ResourceIDUtils.getResourceID();
    }
    this._configManager = new SnkFormConfigManager(this.configName, this.resourceID, undefined, this._dataUnit);
    this.addFormLegacyConfig();
    await this._configManager.loadConfig();
  }
  async handleDataStateChange(evt) {
    var _a;
    this._dataState = evt.detail;
    const fieldsWithRmPrecision = await this._snkDataUnit.getFieldsWithRmPrecision();
    for (const field of fieldsWithRmPrecision || []) {
      if (!field) {
        continue;
      }
      const rmPrecision = (_a = this._dataState.rowMetadata) === null || _a === void 0 ? void 0 : _a.getProp('rm_precision', field);
      if (!rmPrecision && rmPrecision !== 0) {
        continue;
      }
      await this.setFieldProp(field, 'precision', rmPrecision);
      await this.setFieldProp(field, 'prettyPrecision', rmPrecision);
    }
  }
  addFormLegacyConfig() {
    if (this.formLegacyConfigName) {
      this._configManager.addFormLegacyConfig(this.formLegacyConfigName);
    }
  }
  render() {
    if (!this._dataUnit || !this._dataState) {
      return undefined;
    }
    return (h("section", null, h("div", { class: "ez-row" }, h("div", { class: "ez-col ez-col--sd-12" }, h("ez-form", { ref: (ref) => this._form = ref, key: "ezForm" + this._snkDataUnit.entityName, "data-element-id": "embedded", dataUnit: this._dataUnit, config: this._configManager.getConfig(this._dataUnit), recordsValidator: this.recordsValidator, class: this._showFormConfig ? 'snk-form__form--hidden' : '' }), this._showFormConfig &&
      h("snk-form-config", { messagesBuilder: this.messagesBuilder, dataUnit: this._dataUnit, configManager: this._configManager, onConfigClose: () => this.closeConfig() })))));
  }
  get _element() { return this; }
  static get style() { return snkFormCss; }
}, [2, "snk-form", {
    "configName": [1, "config-name"],
    "recordsValidator": [16],
    "messagesBuilder": [1040],
    "formLegacyConfigName": [1, "form-legacy-config-name"],
    "resourceID": [1, "resource-i-d"],
    "_dataUnit": [32],
    "_dataState": [32],
    "_showFormConfig": [32],
    "_configManager": [32],
    "showConfig": [64],
    "hideConfig": [64],
    "addCustomEditor": [64],
    "setFieldProp": [64],
    "validate": [64]
  }]);
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-form", "config-header", "configs-button", "field-config", "field-item", "fields-layout", "fields-selector", "guides-configurator", "snk-form-config"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-form":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkForm$1);
      }
      break;
    case "config-header":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "configs-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "field-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "field-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "fields-layout":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "fields-selector":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "guides-configurator":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "snk-form-config":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
  } });
}

const SnkForm = SnkForm$1;
const defineCustomElement = defineCustomElement$1;

export { SnkForm, defineCustomElement };
