import { ElementIDUtils, NumberUtils, StringUtils } from "@sankhyalabs/core";
import { h } from "@stencil/core";
import CSSVarsUtils from "../../utils/CSSVarsUtils";
import initI18n from '../../utils/i18n';
export class EzNumberInput {
  constructor() {
    this._focused = false;
    this._changePending = false;
    this._valuePromiseCallbacks = [];
    this._value = undefined;
    this.label = undefined;
    this.value = undefined;
    this.enabled = true;
    this.canShowError = true;
    this.errorMessage = undefined;
    this.allowNegative = true;
    this.precision = undefined;
    this.prettyPrecision = undefined;
    this.mode = "regular";
    this.autoFocus = false;
    this.alternativePlaceholder = undefined;
  }
  /**
   * Aplica o foco no campo.
   */
  async setFocus(options) {
    this._textInput.setFocus(options);
  }
  /**
   * Remove o foco do campo.
   */
  async setBlur() {
    this._textInput.setBlur();
  }
  /**
   * Retorna se o conteúdo é inválido.
   */
  async isInvalid() {
    return typeof this.errorMessage === "string" && this.errorMessage.trim() !== "";
  }
  /*
    * Retorna uma promise com o valor da opção selecionada,
    * que será resolvida quando o backend devolver este dado.
    */
  async getValueAsync() {
    if (this._changePending) {
      return new Promise(accept => {
        this._valuePromiseCallbacks.push(accept);
      });
    }
    return Promise.resolve(this.value);
  }
  observeLabel() {
    if (this._textInput) {
      this._textInput.label = this.label;
    }
  }
  observeErrorMessage() {
    var _a;
    if (this._textInput) {
      this._textInput.errorMessage = this.errorMessage;
      if (!((_a = this.errorMessage) === null || _a === void 0 ? void 0 : _a.trim())) {
        this.setInputValue();
      }
    }
  }
  observeValue(newValue, oldValue) {
    if (this._textInput && newValue != oldValue) {
      this.handleNewValue(newValue, oldValue);
    }
    this._changePending = false;
  }
  observePrecision() {
    if (this._textInput) {
      this.setInputValue();
    }
  }
  handleNewValue(newValue, oldValue) {
    const newValueValidated = this.validateValue(newValue);
    const oldValueValidated = this.validateValue(oldValue);
    if (newValueValidated === null) {
      this._value = '';
    }
    if (newValueValidated === oldValueValidated) {
      return;
    }
    const textValue = this.getTextValue(newValueValidated) || '';
    const parsedNumber = this.getParsedNumber(textValue);
    if ((this._value || '') !== textValue && (parsedNumber !== undefined || !this._focused)) {
      this._value = textValue;
      this._focused = false;
      this.errorMessage = "";
    }
    const valueEmitted = newValueValidated === null ? undefined : newValueValidated;
    this.ezChange.emit(valueEmitted);
  }
  validateValue(value) {
    return isNaN(value) || value === undefined ? null : value;
  }
  getTextValue(value) {
    if (value == undefined)
      return undefined;
    let textValue = this.precision >= 0 ? NumberUtils.format(value.toString(), Number(this.precision), Number(this.prettyPrecision)) : value.toString();
    return (this.precision === 0) ? StringUtils.replaceAll(textValue, ".", "") : textValue;
  }
  changeValue(newValue) {
    this.errorMessage = "";
    if (this.value != newValue) {
      this.value = newValue === undefined ? null : newValue;
    }
    else {
      this.setInputValue();
      this.ezCancelWaitingChange.emit();
    }
  }
  setError(msg) {
    this.value = null;
    this.errorMessage = msg;
    this.ezCancelWaitingChange.emit();
  }
  handleBlur() {
    if (!this._changePending) {
      return;
    }
    try {
      const parsedNumber = this.getParsedNumber();
      if (parsedNumber !== undefined && isNaN(parsedNumber)) {
        this.setError(this.i18n("ez-number-input.invalidNumber"));
      }
      else {
        try {
          this.changeValue(parsedNumber);
        }
        catch (e) {
          this.setError(e.message);
          return;
        }
      }
    }
    finally {
      for (const callback of this._valuePromiseCallbacks) {
        callback(this.value);
      }
      this._valuePromiseCallbacks = [];
    }
  }
  handleInput() {
    const parsedNumber = this.getParsedNumber();
    if (parsedNumber !== this.value) {
      this._focused = true;
      this._changePending = true;
      this.ezStartChange.emit({ waitmessage: "", blocking: false });
    }
  }
  getParsedNumber(value = this._textInput.value) {
    return (value === null || value === void 0 ? void 0 : value.trim()) ? NumberUtils.stringToNumber(value) : undefined;
  }
  setInputValue() {
    const textValue = this.getTextValue(this.value) || '';
    if ((this._value || '') !== textValue) {
      this._value = textValue;
      this._textInput.value = this._value;
    }
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  componentDidLoad() {
    CSSVarsUtils.applyVarsTextInput(this._elem, this._textInput);
    this.setInputValue();
    if (this.autoFocus) {
      requestAnimationFrame(() => {
        this.setFocus({ selectText: true });
      });
    }
  }
  render() {
    ElementIDUtils.addIDInfoIfNotExists(this._elem, 'input');
    let restrict = this.precision > 0 ? "0123456789,." : "0123456789";
    if (this.allowNegative) {
      restrict += '-';
    }
    return (h("ez-text-input", { class: "number__input", "data-element-id": ElementIDUtils.getInternalIDInfo("textInput"), ref: elem => this._textInput = elem, "data-slave-mode": "true", label: this.label, onBlur: () => this.handleBlur(), onInput: () => this.handleInput(), restrict: restrict, enabled: this.enabled, errorMessage: this.errorMessage, mode: this.mode, canShowError: this.canShowError, value: this._value, alternativePlaceholder: this.alternativePlaceholder }));
  }
  static get is() { return "ez-number-input"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-number-input.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-number-input.css"]
    };
  }
  static get properties() {
    return {
      "label": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Texto a ser apresentado como t\u00EDtulo do campo."
        },
        "attribute": "label",
        "reflect": false
      },
      "value": {
        "type": "number",
        "mutable": true,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o valor do campo."
        },
        "attribute": "value",
        "reflect": true
      },
      "enabled": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se false, o usu\u00E1rio n\u00E3o pode interagir com o campo."
        },
        "attribute": "enabled",
        "reflect": false,
        "defaultValue": "true"
      },
      "canShowError": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se false deixa de exibir a mensagem de erro dentro do campo."
        },
        "attribute": "can-show-error",
        "reflect": true,
        "defaultValue": "true"
      },
      "errorMessage": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define uma mensagem de orienta\u00E7\u00E3o ao usu\u00E1rio, colocando o campo em modo inv\u00E1lido."
        },
        "attribute": "error-message",
        "reflect": true
      },
      "allowNegative": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se false, o input n\u00E3o aceitar\u00E1 n\u00FAmeros negativos."
        },
        "attribute": "allow-negative",
        "reflect": false,
        "defaultValue": "true"
      },
      "precision": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define quantas casas decimais ser\u00E3o exibidas. Caso haja mais casas haver\u00E1 arredondamento."
        },
        "attribute": "precision",
        "reflect": false
      },
      "prettyPrecision": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define qual \u00E9 o m\u00EDnimo de casas depois da v\u00EDrgula.\nExemplo: 1,1 ser\u00E1 exibido como 1,1000 quando `prettyPrecision = 4`."
        },
        "attribute": "pretty-precision",
        "reflect": false
      },
      "mode": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "\"slim\" | \"regular\"",
          "resolved": "\"regular\" | \"slim\"",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o tamanho do campo."
        },
        "attribute": "mode",
        "reflect": true,
        "defaultValue": "\"regular\""
      },
      "autoFocus": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se true o campo de texto receber\u00E1 o foco ao ser renderizado."
        },
        "attribute": "auto-focus",
        "reflect": false,
        "defaultValue": "false"
      },
      "alternativePlaceholder": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Texto alternativo a ser apresentado como t\u00EDtulo do campo."
        },
        "attribute": "alternative-placeholder",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "_value": {}
    };
  }
  static get events() {
    return [{
        "method": "ezChange",
        "name": "ezChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando acontece a altera\u00E7\u00E3o de valor do campo."
        },
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        }
      }, {
        "method": "ezStartChange",
        "name": "ezStartChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido ao iniciar a altera\u00E7\u00E3o (digita\u00E7\u00E3o incompleta)."
        },
        "complexType": {
          "original": "WaitingChange",
          "resolved": "WaitingChange",
          "references": {
            "WaitingChange": {
              "location": "import",
              "path": "@sankhyalabs/core"
            }
          }
        }
      }, {
        "method": "ezCancelWaitingChange",
        "name": "ezCancelWaitingChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando n\u00E3o foi poss\u00EDvel completar a altera\u00E7\u00E3o entre o evento ezStartChange e ezChange."
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "setFocus": {
        "complexType": {
          "signature": "(options?: TFocusOptions) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "TFocusOptions": {
              "location": "import",
              "path": "../ez-text-input/ez-text-input"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Aplica o foco no campo.",
          "tags": []
        }
      },
      "setBlur": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Remove o foco do campo.",
          "tags": []
        }
      },
      "isInvalid": {
        "complexType": {
          "signature": "() => Promise<boolean>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<boolean>"
        },
        "docs": {
          "text": "Retorna se o conte\u00FAdo \u00E9 inv\u00E1lido.",
          "tags": []
        }
      },
      "getValueAsync": {
        "complexType": {
          "signature": "() => Promise<number>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<number>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_elem"; }
  static get watchers() {
    return [{
        "propName": "label",
        "methodName": "observeLabel"
      }, {
        "propName": "errorMessage",
        "methodName": "observeErrorMessage"
      }, {
        "propName": "value",
        "methodName": "observeValue"
      }, {
        "propName": "precision",
        "methodName": "observePrecision"
      }, {
        "propName": "prettyPrecision",
        "methodName": "observePrecision"
      }];
  }
}
