import { Directive, Attribute, NgModule } from '@angular/core';
/**
 * Cameleão Mask Directive
 *
 * Mask Directive for Ionic Designed to Work with Numbers
 *
 * @example
 *<ion-input type="text" mask="(**) * ****-****"></ion-input>
 *
 *- This will be util to numbers like (77) 9 9933-8525
 *
 */
@Directive({
  selector: '[mask]',
  host: {
    '(keydown)': 'onInputChange($event)'
  }
})
export class MaskDirective {
  private pattern: string;

  /**
   * Gets pattern that will be applied to the entry using the "mask"
   *
   * @param  {string} maskPattern Original Mask
   * @return {void}
   */
  constructor(
    @Attribute("mask") maskPattern: string
  ) {
    this.pattern = maskPattern;
  }

  /**
   * Called when a javascript event with the attribute 'target.value' is triggered (keydown, keyup, keypress)
   *
   * @param {jsEvent} event javascript event with the attribute 'target.value'
   */
  private onInputChange(event): void {
    if (event.keyCode != 8 || event.which != 8 || event.key != "Backspace")
        event.target.value = this.mask(event.target.value)
  }

  /**
   * Applies the mask pattern corresponding to the string and its length
   *
   * @param  {string} origin String to apply the mask pattern
   * @return {string}        String with the mask pattern correspondent
   */
  private mask(origin: string): string {
    var left, right, part = origin.length;

    if (part >= this.pattern.length) return origin.slice(0, this.pattern.length - 1);

    while (this.pattern[part] && this.pattern[part] != '*') {
      left = origin.slice(0, part)
      right = origin.slice(part)
      origin = left + this.pattern[part] + right;
      part = origin.length;
    }

    return origin;
  }
}


@NgModule({
  declarations: [MaskDirective],
  exports: [MaskDirective]
})
export class MaskDirectiveModule {}
