let maxValue: any = null;

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

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

  if (target.value > maxValue) {
    target.value = maxValue;
    target.dispatchEvent(new CustomEvent("input"));
  }
}
