import { Host, h } from '@stencil/core';
import { DateUtils, ElementIDUtils } from '@sankhyalabs/core';
import CSSVarsUtils from '../../utils/CSSVarsUtils';
import initI18n from '../../utils/i18n';
export class EzDateInput {
  constructor() {
    this._changePending = false;
    this._focused = false;
    this._valuePromiseCallbacks = [];
    this.label = undefined;
    this.value = undefined;
    this.enabled = true;
    this.errorMessage = undefined;
    this.mode = "regular";
    this.canShowError = true;
    this.autoFocus = false;
    this.alternativePlaceholder = undefined;
  }
  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) {
      const newValueValidated = DateUtils.validateDate(newValue);
      const oldValueValidated = DateUtils.validateDate(oldValue);
      if ((newValueValidated === null || newValueValidated === void 0 ? void 0 : newValueValidated.getTime()) !== (oldValueValidated === null || oldValueValidated === void 0 ? void 0 : oldValueValidated.getTime())) {
        const textValue = this.getTextValue(newValueValidated) || '';
        const parsedDate = DateUtils.strToDate(textValue);
        if ((parsedDate || !this._focused) && (this._textInput.value || '') !== textValue) {
          this._textInput.value = textValue;
          this._focused = false;
          this.errorMessage = "";
        }
        const valueEmitted = newValueValidated === null ? undefined : newValueValidated;
        this.ezChange.emit(valueEmitted);
      }
    }
    this._changePending = false;
  }
  /**
   * 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);
  }
  changeValue(newValue) {
    const currentValue = DateUtils.validateDate(this.value);
    const newValueValidated = DateUtils.validateDate(newValue);
    if ((currentValue === null || currentValue === void 0 ? void 0 : currentValue.getTime()) !== (newValueValidated === null || newValueValidated === void 0 ? void 0 : newValueValidated.getTime())) {
      this.value = newValueValidated;
    }
    else {
      this._changePending = false;
    }
  }
  hideCalendar() {
    this.changeValue(this._calendar.value);
    this._popover.hide();
  }
  handleBlur() {
    if (!this._changePending) {
      return;
    }
    try {
      const strValue = this._textInput.value;
      const newValue = DateUtils.strToDate(strValue);
      if (newValue || !strValue) {
        this.errorMessage = "";
        const currentValue = DateUtils.validateDate(this.value);
        const newValueValidated = DateUtils.validateDate(newValue);
        if ((currentValue === null || currentValue === void 0 ? void 0 : currentValue.getTime()) === (newValueValidated === null || newValueValidated === void 0 ? void 0 : newValueValidated.getTime())) {
          if (newValueValidated) {
            this._textInput.value = this.getTextValue(newValueValidated) || '';
            this._focused = false;
          }
          this.ezCancelWaitingChange.emit();
        }
        else {
          this._focused = false;
          this.changeValue(newValueValidated);
        }
      }
      else {
        this.changeValue(undefined);
        this.ezCancelWaitingChange.emit();
        this.errorMessage = this.i18n("ez-date-input.invalidDate");
      }
    }
    finally {
      for (const callback of this._valuePromiseCallbacks) {
        callback(this.value);
      }
      this._valuePromiseCallbacks = [];
    }
  }
  getTextValue(d) {
    return d ? DateUtils.formatDate(d) : undefined;
  }
  handleInput(event) {
    const strValue = this._textInput.value;
    const newValue = DateUtils.strToDate(strValue);
    const currentValue = DateUtils.validateDate(this.value);
    const newValueValidated = DateUtils.validateDate(newValue);
    if ((currentValue === null || currentValue === void 0 ? void 0 : currentValue.getTime()) !== (newValueValidated === null || newValueValidated === void 0 ? void 0 : newValueValidated.getTime())) {
      this._changePending = true;
      this._focused = true;
      this.ezStartChange.emit({ waitmessage: "", blocking: false });
    }
    if (event['data'] === "H" || event['data'] === "h") {
      this.changeValue(new Date());
    }
  }
  setInputValue() {
    const textValue = this.getTextValue(this.value) || '';
    if ((this._textInput.value || '') !== textValue) {
      this._textInput.value = textValue;
    }
  }
  disconnectedCallback() {
    this._popover.hide();
  }
  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');
    return (h(Host, null, h("ez-text-input", { "data-element-id": ElementIDUtils.getInternalIDInfo("textInput"), ref: elem => this._textInput = elem, "data-slave-mode": "true", label: this.label, onBlur: () => this.handleBlur(), onInput: (evt) => this.handleInput(evt), restrict: "0123456789/", enabled: this.enabled, errorMessage: this.errorMessage, mode: this.mode, canShowError: this.canShowError, alternativePlaceholder: this.alternativePlaceholder }, h("button", { disabled: !this.enabled, tabindex: -1, class: "btn-open-cal", onClick: () => { var _a; return (_a = this._popover) === null || _a === void 0 ? void 0 : _a.showUnder(this._textInput); }, slot: "leftIcon" })), h("ez-popover-plus", { ref: elem => this._popover = elem, anchorElement: this._textInput, autoClose: true, boxWidth: 'fit-content', overlayType: 'none', "data-element-id": this._elem.getAttribute("data-element-id"), onEzVisibilityChange: (event) => event.stopPropagation() }, h("ez-calendar", { ref: elem => this._calendar = elem, "data-element-id": ElementIDUtils.getInternalIDInfo("calendar"), onEzChange: (event) => { this.hideCalendar(); event.stopPropagation(); } }))));
  }
  static get is() { return "ez-date-input"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-date-input.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-date-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": true
      },
      "value": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "Date",
          "resolved": "Date",
          "references": {
            "Date": {
              "location": "global"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o valor do campo."
        }
      },
      "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
      },
      "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": true
      }
    };
  }
  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": "Date",
          "resolved": "Date",
          "references": {
            "Date": {
              "location": "global"
            }
          }
        }
      }, {
        "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<Date>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            },
            "Date": {
              "location": "global"
            }
          },
          "return": "Promise<Date>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_elem"; }
  static get watchers() {
    return [{
        "propName": "label",
        "methodName": "observeLabel"
      }, {
        "propName": "errorMessage",
        "methodName": "observeErrorMessage"
      }, {
        "propName": "value",
        "methodName": "observeValue"
      }];
  }
}
