import { AbstractControl, ValidatorFn, FormControl, FormGroup } from '@angular/forms';

export class PasswordValidator {
// Inspired on: http://plnkr.co/edit/Zcbg2T3tOxYmhxs7vaAm?p=preview
static equals = (newpasswordControl: AbstractControl): ValidatorFn => {
    let equal: boolean = false;

    return (passwordBisControl: AbstractControl): {[key: string]: boolean} => {
		if(newpasswordControl.value == passwordBisControl.value) {
			return {
				equals: false
			};
		}
		else return {
			equals: true
		};;
	};
}

 static areEqual(formGroup: FormGroup) {
	let val;
	let valid = true;

	for (let key in formGroup.controls) {
		if (formGroup.controls.hasOwnProperty(key)) {
			if(key != "newpassword" && key != "newpasswordbis") continue;
			let control: FormControl = <FormControl>formGroup.controls[key];
			if (val === undefined) {
				val = control.value
			} else {
				if (val !== control.value) {
					valid = false;
					break;
				}
			}
		}
	}
	if (!valid) {
		//return null;
		return {
			areEqual: true
		}
	}
	return null;
 }
}