import { Validator, NG_VALIDATORS, FormControl } from '@angular/forms'
import { Directive, OnInit, forwardRef, Input } from '@angular/core';

import * as Globals from '../globals'; 
 
@Directive({
  selector: '[passwordCheck]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: PasswordCheckValidator, multi: true }
  ]
})
export class PasswordCheckValidator implements Validator, OnInit {

    forbiddenSequences = ['0123', '1234', '2345', '3456', '4567', '5678', '6789', '9876', '4321', '3210',
                          'abcd', 'bcde', 'efgh', 'wxyz', 'heslo', 'password'];

    ngOnInit() {
    }
 
    validate(c: FormControl) {
        
        if(c.value != null) {
            let password: string = c.value;

            var messages: string[] = [];
    
            if (password.length < 6) {
              messages.push('heslo musi mit aspon 6 znaku');
            }

            if (this.includeSequences(password) == true) {
              messages.push('heslo nesmi obsahovat posloupnost po sobe jdoucich pismen nebo cislic ani slova "heslo" a "password"');
            }

            if (this.countUnique(password) < 4) {
              messages.push('heslo musi obsahovat aspon 4 ruzne znaky');
            }

            if(messages.length > 0) {
              return { passwordCheck: true, 'errorMessage': messages.join('  |  ') };
            }
        }
    
        return null;
    }

    includeSequences(password: string): boolean {
      var result = false;
      this.forbiddenSequences.forEach(sequence => {
          if(password.includes(sequence)) {
            result = true;
          }
        }
      );
      return result;
    }

    countUnique(password: string): number {
      var unique: string[] = [];
      for (var i = 0; i < password.length; i++) {
        if(unique.includes(password.charAt(i)) == false) {
          unique.push(password.charAt(i));
        };
      }
      return unique.length;
    }
}