import IMask from "imask";

export const MaskDirective = {
  beforeMount(el: HTMLElement, binding: any) {
    if (
      Object.prototype.hasOwnProperty.call(binding, "value") &&
      binding.value
    ) {
      el.addEventListener("input", ev => {
        ev.preventDefault();
      });

      const maskOptions = binding.value;
      const mask = IMask(el, maskOptions);

      mask.on("accept", () => {
        dispatchValue(el, mask);
      });

      mask.on("complete", () => {
        el.dispatchEvent(new CustomEvent("complete"));
      });

      mask.updateValue();
    }
  }
};

function dispatchValue(el: HTMLElement, mask: IMask.InputMask<any>): void {
  el.dispatchEvent(
    new CustomEvent("accept", {
      detail: {
        value: mask.value,
        unmasked: mask.unmaskedValue
      }
    })
  );
}
