import {FormGroup} from "@angular/forms";

export function TimeValid(time_init: string, time_final: string) {
	return (formGroup: FormGroup) => {
		const TIME_INIT = formGroup.controls[time_init];
		const TIME_FINAL = formGroup.controls[time_final];

		if (TIME_INIT.errors && !TIME_INIT.errors.time_invalid) {
			return;
		}
		if (TIME_FINAL.errors && !TIME_FINAL.errors.time_invalid) {
			return;
		}
		if (!TIME_INIT.value){
			return;
		}
		if (!TIME_FINAL.value){
			return;
		}

		let time_init_array:Array<number> = TIME_INIT.value.split(':');
		let time_final_array:Array<number> = TIME_FINAL.value.split(':');

		if (time_init_array.length != 2){
			TIME_INIT.setErrors({time_invalid: true});
		}else {
			TIME_INIT.setErrors(null);
		}

		if (time_final_array.length != 2){
			TIME_FINAL.setErrors({time_invalid: true});
		}else {
			TIME_FINAL.setErrors(null);
		}
	}
}

export function TimeValanced(time_init: string, time_final: string) {
	return (formGroup: FormGroup) => {
		const TIME_INIT = formGroup.controls[time_init];
		const TIME_FINAL = formGroup.controls[time_final];

		if (TIME_INIT.errors && !TIME_INIT.errors.time_invalid) {
			return;
		}
		if (TIME_FINAL.errors && !TIME_FINAL.errors.time_invalid) {
			return;
		}
		if (!TIME_INIT.value){
			return;
		}
		if (!TIME_FINAL.value){
			return;
		}

		let time_init_array:Array<number> = TIME_INIT.value.split(':');
		let time_final_array:Array<number> = TIME_FINAL.value.split(':');

		if (time_init_array.length == 2){
			if (time_init_array[0] == time_final_array[0]){
				if (time_init_array[1] >= time_final_array[1]){
					TIME_INIT.setErrors({time_init_minute: true});
				}else {
					TIME_INIT.setErrors(null);
				}
			}else if (time_init_array[0] > time_final_array[0]){
				TIME_INIT.setErrors({time_init_invalid: true});
			}else {
				TIME_INIT.setErrors(null);
				TIME_FINAL.setErrors(null);
			}
		}else return;
	}
}
