import IMask from 'imask';


export
const IMaskDirective = {
  name: 'imask',

  bind (el, {value: options}) {
    if (!options) return;

    initMask(el, options);
  },

  update (el, {value: options}) {
    if (options) {
      if (el.maskRef) el.maskRef.updateOptions(options);
      else initMask(el, options);
    } else {
      destroyMask(el);
    }
  },

  unbind (el) {
    destroyMask(el);
  }
};


function fireEvent (el, eventName, data) {
  var e = document.createEvent('CustomEvent');
  e.initCustomEvent(eventName, true, true, data);
  el.dispatchEvent(e);
}

function initMask (el, opts) {
  el.maskRef = new IMask(el, opts)
    .on('accept', () => {
      fireEvent(el, 'accept', el.maskRef);
    })
    .on('complete', () => {
      fireEvent(el, 'complete', el.maskRef);
    });
}

function destroyMask (el) {
  if (el.maskRef) {
    el.maskRef.destroy();
    delete el.maskRef;
  }
}

@@ -238,16 +238,26 @@
 maskRef)
+ %7B%0A       
  el.mask
@@ -280,24 +280,99 @@
 s(options);%0A
+        if (el.value !== el.maskRef.value) el.maskRef._onChange();%0A      %7D%0A
       else i
@@ -486,17 +486,16 @@
   %7D%0A%7D;%0A%0A
-%0A
 function
@@ -737,32 +737,24 @@
 cept', () =%3E
- %7B%0A     
  fireEvent(e
@@ -777,23 +777,16 @@
 maskRef)
-;%0A    %7D
 )%0A    .o
@@ -804,24 +804,16 @@
 ', () =%3E
- %7B%0A     
  fireEve
@@ -842,23 +842,16 @@
 maskRef)
-;%0A    %7D
 );%0A%7D%0A%0Afu

fix #249, fix #252