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 uniqMobileValidator(validatorService: ValidatorService, type: string, referenceIdKey: string): AsyncValidatorFn {
    return (control: FormControl): Promise<ValidationErrors | (Object | null)> | Observable<ValidationErrors | (Object | null)> => {
        return timer(500).pipe(
            switchMap(() => {
                const countryId: number = (control.parent.controls as any)["countryId"] ? (control.parent.controls as any)["countryId"].value : 0;
                const referenceId: number = (control.parent.controls as any)[referenceIdKey] ? (control.parent.controls as any)[referenceIdKey].value : 0;
                return validatorService.validateMobile(control.value, countryId || 0, type, referenceId)
                    .pipe(
                        map((res: boolean) => {
                            return res && control.value !== null ? { mobileExists: true } : null;
                        })
                    );
            })
        );
    };
}
