import { proxyCustomElement, HTMLElement, h } from '@stencil/core/internal/client';
import { ApplicationContext } from '@sankhyalabs/core';

class ServicesNumberingConfig {
  constructor(application, resourceID) {
    this._application = application;
    this._resourceID = resourceID;
  }
  async getResourceID() {
    if (!this._resourceID) {
      this._resourceID = await this._application.getResourceID();
    }
    return this._resourceID;
  }
  async getConfig(entityName) {
    const serviceName = "DynaformBuilder.getNumberConfig";
    const response = await this._application.callServiceBroker(serviceName, {
      paramsConfig: {
        resourceID: await this.getResourceID(),
        entityName
      }
    });
    return {
      isAutoNumbering: response.config.isAutoNum === "true",
      initialNumber: Number(response.config.numeroInicial)
    };
  }
  async saveConfig(payload) {
    const serviceName = "DynaformBuilder.saveNumberConfig";
    return this._application.callServiceBroker(serviceName, {
      paramsConfig: Object.assign({ resourceID: await this.getResourceID() }, payload)
    });
  }
}

const snkNumberingConfigCss = ".sc-snk-numbering-config-h{display:block}";

const SnkNumberingConfig = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.handleNumberingConfigChanged = (event) => {
      const config = event.detail;
      if (config) {
        this.applyConfiguration(config);
      }
    };
    this.autoNumbering = false;
    this.initialNumber = undefined;
    this.messagesBuilder = undefined;
    this.entityName = undefined;
    this.resourceID = undefined;
  }
  /**
   * Salva ou recupera as configurações de numeração.
   */
  async save() {
    try {
      if (this._savedConfig && this._savedConfig.isAutoNumbering === this.autoNumbering && this._savedConfig.initialNumber === this.initialNumber) {
        return true;
      }
      const payload = {
        entityName: this.entityName,
        isAutoNum: this.autoNumbering,
        numInicial: this.initialNumber
      };
      await this._servicesNumberingConfig.saveConfig(payload);
      this._savedConfig = {
        isAutoNumbering: this.autoNumbering,
        initialNumber: this.initialNumber
      };
      if (this._snkCrud && this._snkCrud.updateNumberingConfig) {
        await this._snkCrud.updateNumberingConfig(this._savedConfig);
      }
      return true;
    }
    catch (error) {
      console.error("Error saving numbering config:", error);
      return false;
    }
  }
  async componentWillLoad() {
    const _application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this.findParentSnkCrud();
    this._servicesNumberingConfig = new ServicesNumberingConfig(_application, this.resourceID);
    if (this.entityName) {
      await this.loadNumberingConfiguration();
    }
  }
  findParentSnkCrud() {
    const snkCrudElement = this._element.closest('snk-crud');
    if (snkCrudElement) {
      this._snkCrud = snkCrudElement;
      this._snkCrud.addEventListener('numberingConfigChanged', this.handleNumberingConfigChanged.bind(this));
    }
  }
  async loadNumberingConfiguration() {
    try {
      const configFromCrud = await this.tryGetConfigFromSnkCrud();
      if (configFromCrud) {
        this.applyConfiguration(configFromCrud);
        return;
      }
      const configFromService = await this.loadConfigFromService();
      this.applyConfiguration(configFromService);
      await this.updateSnkCrudConfig(configFromService);
    }
    catch (error) {
      console.error("Error loading numbering config:", error);
      this.setDefaultConfiguration();
    }
  }
  async tryGetConfigFromSnkCrud() {
    if (!this._snkCrud) {
      return null;
    }
    try {
      const config = await this._snkCrud.getNumberingConfig();
      if (config) {
        return config;
      }
    }
    catch (error) {
      console.log("snk-crud não tem configuração ainda, carregando diretamente...");
    }
    return null;
  }
  async loadConfigFromService() {
    return await this._servicesNumberingConfig.getConfig(this.entityName);
  }
  applyConfiguration(config) {
    this._savedConfig = config;
    this.autoNumbering = config.isAutoNumbering;
    this.initialNumber = config.initialNumber;
  }
  async updateSnkCrudConfig(config) {
    if (this._snkCrud) {
      try {
        await this._snkCrud.updateNumberingConfig(config);
      }
      catch (error) {
        console.warn("Erro ao atualizar configuração no snk-crud:", error);
      }
    }
  }
  setDefaultConfiguration() {
    this.autoNumbering = false;
    this.initialNumber = null;
  }
  getMessage(key, params) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
  }
  disconnectedCallback() {
    if (this._snkCrud) {
      this._snkCrud.removeEventListener('numberingConfigChanged', this.handleNumberingConfigChanged);
    }
  }
  render() {
    return (h("div", { class: "ez-flex ez-flex--column" }, h("ez-check", { mode: 'SWITCH', label: this.getMessage('snkNumberingConfig.labelAutoNumbering'), class: "ez-margin-bottom--medium", onEzChange: ({ detail }) => this.autoNumbering = detail, value: this.autoNumbering }), h("ez-number-input", { label: this.getMessage('snkNumberingConfig.labelInitialNumber'), onEzChange: ({ detail }) => this.initialNumber = detail, value: this.initialNumber, precision: 0, prettyPrecision: 0, allowNegative: false, enabled: this.autoNumbering })));
  }
  get _element() { return this; }
  static get style() { return snkNumberingConfigCss; }
}, [2, "snk-numbering-config", {
    "messagesBuilder": [16],
    "entityName": [1, "entity-name"],
    "resourceID": [1, "resource-i-d"],
    "autoNumbering": [32],
    "initialNumber": [32],
    "save": [64]
  }]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["snk-numbering-config"];
  components.forEach(tagName => { switch (tagName) {
    case "snk-numbering-config":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, SnkNumberingConfig);
      }
      break;
  } });
}

export { ServicesNumberingConfig as S, SnkNumberingConfig as a, defineCustomElement as d };
