import { h, Host } from "@stencil/core";
import { TimeFormatter, MaskFormatter, NumberUtils, ElementIDUtils } from "@sankhyalabs/core";
import CSSVarsUtils from "../../utils/CSSVarsUtils";
import initI18n from '../../utils/i18n';
export class EzTimeInput {
  constructor() {
    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 is() { return "ez-time-input"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-time-input.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-time-input.css"]
    };
  }
  static get assetsDirs() { return ["../assets"]; }
  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": true
      },
      "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": false
      },
      "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": 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
      },
      "showSeconds": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Se true considera segundos."
        },
        "attribute": "show-seconds",
        "reflect": true,
        "defaultValue": "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\""
      },
      "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"
      },
      "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 ser apresentado como t\u00EDtulo do campo."
        },
        "attribute": "alternative-placeholder",
        "reflect": false
      }
    };
  }
  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": "({ selectText }: 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": []
        }
      }
    };
  }
  static get elementRef() { return "_elem"; }
  static get watchers() {
    return [{
        "propName": "errorMessage",
        "methodName": "observeErrorMessage"
      }, {
        "propName": "showSeconds",
        "methodName": "observeShowSeconds"
      }, {
        "propName": "value",
        "methodName": "observeValue"
      }];
  }
}
