import { Attribute, Directive, Input } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn } from '@angular/forms';
import { ValidationErrors } from '@angular/forms/src/directives/validators';

import { CoreModule } from '../../core';

export function patternValidator(regexp: RegExp): ValidatorFn {
  return (control: AbstractControl): { [key: string]: ValidationErrors } => {
    const value: string = control.value;
    if (value === '') {
      return null;
    }
    return !regexp.test(value) ? { patternInvalid: { regexp } } : null;
  };
}

@Directive({
  selector: '[knkEmail]',
  providers: [{provide: NG_VALIDATORS, useExisting: EmailDirective, multi: true}]
})

export class EmailDirective implements Validator {
  // constructor( @Input('knkAppForbiddenName') public knkAppForbiddenName: string) {}
  // @Input('knkAppForbiddenName') knkAppForbiddenName: string = 'ddddd';

  validate(control: AbstractControl): {[key: string]: string} {
    if (control.value) {
      return patternValidator(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
    (control);
    }
  }
}
