import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-baa5e267.js';
import { TimeFormatter, MaskFormatter, NumberUtils, ElementIDUtils } from '@sankhyalabs/core';
import { C as CSSVarsUtils } from './CSSVarsUtils-acba92d7.js';
import { i as initI18n } from './index-41363fa6.js';

const ezTimeInputCss = ":host{display:flex;flex-wrap:wrap;position:relative;width:100%}.time__input{height:100%}";

const EzTimeInput = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezChange = createEvent(this, "ezChange", 7);
    this.ezStartChange = createEvent(this, "ezStartChange", 7);
    this.ezCancelWaitingChange = createEvent(this, "ezCancelWaitingChange", 7);
    this.label = undefined;
    this.value = undefined;
    this.enabled = true;
    this.errorMessage = undefined;
    this.showSeconds = false;
    this.mode = "regular";
    this.canShowError = true;
    this.autoFocus = false;
    this.alternativePlaceholder = undefined;
  }
  observeErrorMessage() {
    var _a;
    if (this._textInput) {
      this._textInput.errorMessage = this.errorMessage;
      if (!((_a = this.errorMessage) === null || _a === void 0 ? void 0 : _a.trim())) {
        this.prepareValue(this._viewValue);
        if ((this._textInput.value || '') !== this._viewValue) {
          this._textInput.value = this._viewValue;
        }
      }
    }
  }
  observeShowSeconds() {
    if (this.showSeconds) {
      this.prepareMask("##:##:##");
    }
    else {
      this.prepareMask("##:##");
    }
  }
  observeValue(newValue, oldValue) {
    if (this._textInput && newValue != oldValue) {
      let newValueValidated = this.validateValue(newValue);
      const oldValueValidated = this.validateValue(oldValue);
      if (newValueValidated != oldValueValidated) {
        this._viewValue = newValueValidated == undefined ? "" : newValueValidated.toString();
        this.prepareValue(this._viewValue);
        if (this._viewValue && !TimeFormatter.validateTime(this._viewValue, this.showSeconds)) {
          this.setError(this.i18n("ez-time-input.invalidTime"));
          newValueValidated = undefined;
        }
        else {
          this.setError("");
        }
        const valueEmitted = newValueValidated === null ? undefined : newValueValidated;
        this.ezChange.emit(valueEmitted);
      }
    }
  }
  //---------------------------------------------
  // Private methods
  //---------------------------------------------
  prepareMask(mask) {
    if (this._maskFormatter == undefined) {
      this._maskFormatter = new MaskFormatter(mask);
    }
    else {
      this._maskFormatter.mask = mask;
    }
  }
  validateValue(value) {
    return isNaN(value) || value === undefined ? null : value;
  }
  setError(msg) {
    this.errorMessage = msg;
    if (this._textInput && (msg === null || msg === void 0 ? void 0 : msg.trim())) {
      this.ezCancelWaitingChange.emit();
    }
  }
  //---------------------------------------------
  // Public methods
  //---------------------------------------------
  getViewValue() {
    return this._viewValue;
  }
  prepareValue(value) {
    try {
      this._viewValue = TimeFormatter.prepareValue(value, this.showSeconds);
      if (this._textInput && this._textInput.value !== this._viewValue) {
        this._textInput.value = this._viewValue;
      }
    }
    catch (e) {
      this.setError(e.message);
    }
  }
  /**
   * Aplica o foco no campo.
   */
  async setFocus({ selectText }) {
    this._textInput.setFocus({ selectText });
  }
  /**
   * 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() !== "";
  }
  //---------------------------------------------
  // Event handlers
  //---------------------------------------------
  handleBlur() {
    if (this._textInput) {
      this._viewValue = this._textInput.value;
      this.prepareValue(this._viewValue);
      const value = NumberUtils.stringToNumber(this._viewValue.replace(/\D/g, ""));
      this.value = ['string', 'number'].includes(typeof value) ? value : null;
    }
  }
  handleInput() {
    const textInputValue = this._textInput.value;
    if (!['string', 'number'].includes(typeof textInputValue))
      return;
    const parsedNumber = NumberUtils.stringToNumber(textInputValue.replace(/\D/g, ""));
    if (parsedNumber !== this.value) {
      this.ezStartChange.emit({ waitmessage: "", blocking: false });
    }
  }
  //---------------------------------------------
  // Lifecycle web component
  //---------------------------------------------
  async componentWillLoad() {
    this.i18n = await initI18n();
    this.observeShowSeconds();
    if (this.value) {
      this.prepareValue(this.value.toString());
    }
    else if (this._viewValue) {
      this.prepareValue(this._viewValue);
    }
  }
  componentDidLoad() {
    CSSVarsUtils.applyVarsTextInput(this._elem, this._textInput);
    if (this.autoFocus) {
      requestAnimationFrame(() => {
        this.setFocus({ selectText: true });
      });
    }
  }
  render() {
    ElementIDUtils.addIDInfoIfNotExists(this._elem, 'input');
    return (h(Host, null, h("ez-text-input", { class: "time__input", "data-element-id": ElementIDUtils.getInternalIDInfo("textInput"), ref: (el) => this._textInput = el, "data-slave-mode": "true", value: this._viewValue, enabled: this.enabled, label: this.label, restrict: "0123456789:", onBlur: () => this.handleBlur(), onInput: () => this.handleInput(), errorMessage: this.errorMessage, mode: this.mode, canShowError: this.canShowError, alternativePlaceholder: this.alternativePlaceholder }, h("ez-icon", { slot: "leftIcon", iconName: "timer-outline" }))));
  }
  static get assetsDirs() { return ["../assets"]; }
  get _elem() { return getElement(this); }
  static get watchers() { return {
    "errorMessage": ["observeErrorMessage"],
    "showSeconds": ["observeShowSeconds"],
    "value": ["observeValue"]
  }; }
};
EzTimeInput.style = ezTimeInputCss;

export { EzTimeInput as ez_time_input };
