export const MaxLengthDirective = {
  beforeMount(el: HTMLElement, binding: any) {
    if (
      Object.prototype.hasOwnProperty.call(binding, "value") &&
      binding.value
    ) {
      const maxLength = binding.value;
      let value = "";
      el.addEventListener("input", inputHandler.bind({ maxLength, value }));
    }
  },
  unmounted(el: HTMLElement) {
    el.removeEventListener("input", inputHandler);
  }
};

function inputHandler(event: Event) {
  const target = event.target as HTMLInputElement;
  const selectionPos = target.selectionStart as any;

  if (target.value.length > this.maxLength) {
    target.value = this.value;
    target.dispatchEvent(new CustomEvent("input"));
    target.setSelectionRange(selectionPos - 1, selectionPos - 1);
    return;
  }

  this.value = target.value;
}
