import {AbstractControl, AsyncValidatorFn, ValidationErrors} from '@angular/forms';
import { Observable, of } from 'rxjs';
import {AuthService} from '../service/auth.service';
import {delay, map, switchMap} from 'rxjs/operators';



export function asyncValidatorLoginAvailable(auth: AuthService, existing: string): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors> | null => {
    const v: string = control.value;

    if (v === existing && v !== '') {
      return of(null);
    }

    return of(control.value).pipe(
      delay(500),
      switchMap( () => auth.LoginAvailable(v).pipe(
          map((result: boolean) => result ? null : {loginAvailable: true})
        )
      )
    );
  };
}

