import { Directive, ElementRef, HostListener, Optional, Self, Inject } from '@angular/core';
import { ControlValueAccessor, DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Directive({
  selector: '[inputCleanWhitespaces]',
  exportAs: 'inputCleanWhitespaces'
})
export class InputCleanWhitespacesDirective {
  constructor(private elementRef: ElementRef,
              @Optional() @Self() @Inject(NG_VALUE_ACCESSOR)
              private controlValueAccessors: ControlValueAccessor[]) {
  }

  @HostListener('input', [ '$event' ])
  onInput(event: InputEvent): void {
    let target: HTMLInputElement | undefined = event.target as HTMLInputElement;
    if (target) {
      if (target.tagName === 'INPUT') {
        switch (target.type) {
          case 'text':
          case 'email':
          case 'number':
            target.value = target.value.replace(/\s+/g, '');
            if (Array.isArray(this.controlValueAccessors)) {
              this.controlValueAccessors.forEach((controlValueAccessor: ControlValueAccessor): void => {
                let handler: string = 'onChange';
                if (typeof controlValueAccessor[handler] === 'function') {
                  controlValueAccessor[handler](target.value);
                }
              });
            }
            break;
          default:
        }
      }
    }
  }
}
