import { AsyncValidatorFn, FormControl, ValidationErrors } from "@angular/forms";
import { Observable, timer } from "rxjs";
import { map, switchMap } from "rxjs/operators";
import { ValidatorService } from "@shared/services";


export function uniqUserNameValidator(validatorService: ValidatorService, type: string, referenceIdKey: string): AsyncValidatorFn {
    return (control: FormControl): Promise<ValidationErrors | (Object | null)> | Observable<ValidationErrors | (Object | null)> => {
        return timer(500).pipe(
            switchMap(() => {
                const referenceId: number = (control.parent.controls as any)[referenceIdKey] ? (control.parent.controls as any)[referenceIdKey].value : 0;
                return validatorService.validateUserName(control.value, type, referenceId)
                    .pipe(
                        map((res: boolean) => {
                            return res ? { userNameExists: true } : null;
                        })
                    );
            })
        );
    };
}