import { Component, Element, Event, h, Listen, Prop, State } from "@stencil/core";
import { modifiersToClass, regexValidators } from '../../utils/utils';
export class IbkTextfield {
  constructor() {
    /** Tipo de contenido que se ingresará en el campo de texto */
    this.type = 'text';
    /** Cuando se encuentra dentro de un "ibk-form" al hacer submit si el campo de texto se encuentra vacío, mostrará un mensaje de error */
    this.required = false;
    /** Personaliza el mensaje de campo requerido */
    this.requiredMessage = 'Este campo es requerido';
    /** Se mostrará un mensaje de error */
    this.error = false;
    /** Personaliza el mensaje de error */
    this.errorMessage = 'Por favor, ingrese este campo correctamente';
    /** Contenido del campo de texto */
    this.value = '';
    /** Define si el textfield no contará con manejo de errores. Se omitirá el espacio generado para el mensaje de error */
    this.noHandlingError = false;
    /** Estado que determina si el campo de texto ha sido tocado o no */
    this.touched = false;
    /** Muestra un icono a la izquierda con una X que sirve para borrar el contenido del campo de texto */
    this._erasable = false;
    /** Estado activo o inactivo del campo de texto */
    this._focus = false;
    /** Estado que determina si la contraseña está visible o no */
    this._showingPwd = false;
    /** Configura el tipo de campo de texto en base a la configuración del componente */
    this.setInputType = () => {
      let type = '';
      if (this.type == 'password' && !this._showingPwd) {
        type = 'password';
      }
      else if (this.type == 'date') {
        type = this.type;
      }
      else {
        type = 'text';
      }
      return type;
    };
    /** Define el máximo de caracteres en base a la configuración del componente */
    this.setMaxLength = () => {
      let length = 0;
      if (this.type == 'expiration') {
        length = 5;
      }
      else if (this.type == 'cvv') {
        length = 4;
      }
      else if (this.type == 'dni') {
        length = 8;
      }
      else if (this.type == 'document') {
        length = 16;
      }
      else if (this.type == 'phone') {
        length = 9;
      }
      return length;
    };
    /** Configura el icono del lado izquierdo en base a la configuración del componente */
    this.setTrailingIcon = () => {
      let icon = '';
      if (this.type == 'password') {
        icon = this._showingPwd ? 'icon-m-eye-off' : 'icon-m-eye-on';
      }
      else if (this._erasable) {
        icon = 'icon-m-status-error';
      }
      else if (this.trailingIcon) {
        icon = this.trailingIcon;
      }
      return icon;
    };
    /** Determina la función a realizar en base al icono actual */
    this.trailingIconFunction = () => {
      if (this.type == 'password') {
        this._showingPwd = !this._showingPwd;
      }
      else if (this._erasable) {
        const input = this.host.querySelector('.ibk-textfield__value');
        input.value = '';
        this._erasable = false;
      }
    };
    /** Determina el mensaje de error a mostrar en base a la configuración del componente */
    this.setErrorMessage = () => {
      let msg = '';
      if (this.required && this.error && this.value.length == 0) {
        msg = this.requiredMessage;
      }
      else if (this.error) {
        msg = this.errorMessage;
      }
      return msg;
    };
    /** Valida el campo de texto después de haber sido tocado */
    this._validateTouchedInput = () => {
      if (this.touched) {
        let regex;
        switch (this.type) {
          case 'phone':
            regex = regexValidators.number;
            break;
          case 'password':
          case 'text':
          case 'date':
            regex = regexValidators.empty;
            break;
          default: regex = regexValidators[this.type];
        }
        if (!regex.test(this.value)) {
          this.host.setAttribute('error', '');
          this.setErrorMessage();
        }
        else {
          this.host.removeAttribute('error');
        }
      }
    };
    /** Escucha y emite el evento editing cuando cambia el contenido */
    this.onInputChange = (e) => {
      const t = e.target;
      this.value = t.value;
      this._erasable = this.value != '' ? true : false;
      if (this.type == 'expiration' && t.value.length == 2 && this._keyCode != 8) {
        this.value += '/';
      }
      if (this._grouper != null) {
        this._grouper.removeAttribute('error');
      }
      this.onchange.emit(t.value);
    };
  }
  componentWillLoad() {
    this._grouper = this.host.closest('ibk-form-group');
  }
  onInputFocusIn() {
    this._focus = true;
    this.onfocus.emit('in');
  }
  onInputFocusOut() {
    this._focus = false;
    this.onfocus.emit('out');
    this.host.setAttribute('touched', '');
    this._validateTouchedInput();
    /** Validación para fecha de expiración */
    if (this.type == 'expiration' && this.value.length == 5) {
      const exp = this.value.split('/');
      const currentYear = new Date().getFullYear().toString();
      const formatYear = currentYear.slice(2);
      if (parseInt(exp[0]) > 12 || parseInt(exp[1]) < parseInt(formatYear)) {
        this.host.setAttribute('error', '');
      }
    }
  }
  /** Configura la clase del componente basado en estados y modificadores */
  containerClass() {
    return modifiersToClass('ibk-textfield', [
      this.type,
      { focus: this._focus },
      { erasable: this._erasable },
      { error: this.error },
      { disabled: this.disabled }
    ]);
  }
  onKeyDown(e) {
    this._keyCode = e.keyCode;
    if (['expiration', 'cvv', 'dni'].includes(this.type) && !regexValidators.number.test(e.key) && (this._keyCode != 8 && this._keyCode != 9)) {
      e.preventDefault();
    }
    else if (this.type == 'number' && !regexValidators.numberFormat.test(e.key) && (this._keyCode != 8 && this._keyCode != 9)) {
      e.preventDefault();
    }
  }
  onKeyUp() { this._validateTouchedInput(); }
  render() {
    var _a;
    return (h("div", { class: this.containerClass(), style: { width: this.width + 'px' } },
      this.label && h("span", { class: "ibk-textfield__label", innerHTML: this.label }),
      this.subtitle && h("span", { class: "ibk-textfield__subtitle", innerHTML: this.subtitle }),
      h("label", { class: "ibk-textfield__input" },
        this.leadingIcon && h("i", { class: 'ibk-textfield__leading-icon ' + this.leadingIcon }),
        h("input", { class: "ibk-textfield__value", type: this.setInputType(), placeholder: this.placeholder, maxLength: (_a = this.maxLength) !== null && _a !== void 0 ? _a : (this.setMaxLength() > 0 ? this.setMaxLength() : null), value: this.value, onInput: this.onInputChange }),
        this.setTrailingIcon() != '' && h("i", { class: 'ibk-textfield__trailing-icon ' + this.setTrailingIcon(), onClick: this.trailingIconFunction })),
      !this.noHandlingError && h("span", { class: "ibk-textfield__error-message", innerHTML: this.setErrorMessage() })));
  }
  static get is() { return "ibk-textfield"; }
  static get originalStyleUrls() { return {
    "$": ["textfield.css"]
  }; }
  static get styleUrls() { return {
    "$": ["textfield.css"]
  }; }
  static get properties() { return {
    "placeholder": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Texto de ayuda dentro del campo de texto"
      },
      "attribute": "placeholder",
      "reflect": false
    },
    "label": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Texto de ayuda encima del campo de texto"
      },
      "attribute": "label",
      "reflect": false
    },
    "type": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'text' | 'password' | 'dni' | 'document' | 'email' | 'number' | 'expiration' | 'cvv' | 'phone' | 'date'",
        "resolved": "\"cvv\" | \"date\" | \"dni\" | \"document\" | \"email\" | \"expiration\" | \"number\" | \"password\" | \"phone\" | \"text\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Tipo de contenido que se ingresar\u00E1 en el campo de texto"
      },
      "attribute": "type",
      "reflect": false,
      "defaultValue": "'text'"
    },
    "trailingIcon": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Icono posicionado a la derecha del campo de texto"
      },
      "attribute": "trailing-icon",
      "reflect": false
    },
    "leadingIcon": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Icono posicionado a la izquierda del campo de texto"
      },
      "attribute": "leading-icon",
      "reflect": false
    },
    "required": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Cuando se encuentra dentro de un \"ibk-form\" al hacer submit si el campo de texto se encuentra vac\u00EDo, mostrar\u00E1 un mensaje de error"
      },
      "attribute": "required",
      "reflect": false,
      "defaultValue": "false"
    },
    "requiredMessage": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Personaliza el mensaje de campo requerido"
      },
      "attribute": "required-message",
      "reflect": false,
      "defaultValue": "'Este campo es requerido'"
    },
    "error": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Se mostrar\u00E1 un mensaje de error"
      },
      "attribute": "error",
      "reflect": false,
      "defaultValue": "false"
    },
    "errorMessage": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Personaliza el mensaje de error"
      },
      "attribute": "error-message",
      "reflect": false,
      "defaultValue": "'Por favor, ingrese este campo correctamente'"
    },
    "value": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Contenido del campo de texto"
      },
      "attribute": "value",
      "reflect": false,
      "defaultValue": "''"
    },
    "subtitle": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Se incluye el subtitulo entre el label (si existiera) y el campo de texto"
      },
      "attribute": "subtitle",
      "reflect": false
    },
    "width": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Configura un ancho fijo para el componente"
      },
      "attribute": "width",
      "reflect": false
    },
    "disabled": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "El campo de texto no se podr\u00E1 editar"
      },
      "attribute": "disabled",
      "reflect": false
    },
    "maxLength": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Define la cantidad m\u00E1xima de caracteres en el componente"
      },
      "attribute": "max-length",
      "reflect": false
    },
    "noHandlingError": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Define si el textfield no contar\u00E1 con manejo de errores. Se omitir\u00E1 el espacio generado para el mensaje de error"
      },
      "attribute": "no-handling-error",
      "reflect": false,
      "defaultValue": "false"
    },
    "touched": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Estado que determina si el campo de texto ha sido tocado o no"
      },
      "attribute": "touched",
      "reflect": false,
      "defaultValue": "false"
    }
  }; }
  static get states() { return {
    "_erasable": {},
    "_focus": {},
    "_showingPwd": {},
    "_grouper": {}
  }; }
  static get events() { return [{
      "method": "onchange",
      "name": "onchange",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Emite un evento mientras se escribe en el campo de texto, env\u00EDa el contenido actual como par\u00E1metro"
      },
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      }
    }, {
      "method": "onfocus",
      "name": "onfocus",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Emite un evento al hacer focusin o focusout del campo de texto, env\u00EDa como detalle \"out\" o \"in\""
      },
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      }
    }]; }
  static get elementRef() { return "host"; }
  static get listeners() { return [{
      "name": "focusin",
      "method": "onInputFocusIn",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "focusout",
      "method": "onInputFocusOut",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "keydown",
      "method": "onKeyDown",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "keyup",
      "method": "onKeyUp",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
