import { ApplicationContext } from '@sankhyalabs/core';
import { h } from '@stencil/core';
import { ServicesNumberingConfig } from './services/ServicesNumberingConfig';
export class SnkNumberingConfig {
  constructor() {
    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 })));
  }
  static get is() { return "snk-numbering-config"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-numbering-config.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-numbering-config.css"]
    };
  }
  static get properties() {
    return {
      "messagesBuilder": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "SnkMessageBuilder",
          "resolved": "SnkMessageBuilder",
          "references": {
            "SnkMessageBuilder": {
              "location": "import",
              "path": "../../lib/message/SnkMessageBuilder"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Usado para exibir os mensagens de configura\u00E7\u00E3o."
        }
      },
      "entityName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Nome da entidade que est\u00E1 sendo configurada."
        },
        "attribute": "entity-name",
        "reflect": false
      },
      "resourceID": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Identificador de recursos como configura\u00E7\u00F5es e acesso."
        },
        "attribute": "resource-i-d",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "autoNumbering": {},
      "initialNumber": {}
    };
  }
  static get methods() {
    return {
      "save": {
        "complexType": {
          "signature": "() => Promise<boolean>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            },
            "PayloadSaveConfig": {
              "location": "import",
              "path": "./services/ServicesNumberingConfig"
            }
          },
          "return": "Promise<boolean>"
        },
        "docs": {
          "text": "Salva ou recupera as configura\u00E7\u00F5es de numera\u00E7\u00E3o.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_element"; }
}
