import { of, from } from 'rxjs';
import { isAsyncValidator, createAsyncValidator, } from '..';
import { switchMap } from 'rxjs/operators';
import { markForRequired, isRequiredValidator } from '../validators';
export function when(condition) {
    return function (validator) {
        var next = isAsyncValidator(validator)
            ? createAsyncValidator(function (value, context) {
                return condition(context)
                    ? validator.validator(value, context)
                    : null;
            })
            : function (value, context) {
                return condition(context) ? validator(value, context) : null;
            };
        isRequiredValidator(validator) && markForRequired(next);
        return next;
    };
}
export function whenAsync(condition) {
    return function (validator) {
        var next = createAsyncValidator(function (value, context) {
            return from(condition(context)).pipe(switchMap(function (shouldValidate) {
                if (shouldValidate) {
                    return isAsyncValidator(validator)
                        ? validator.validator(value, context) || of(null)
                        : of(validator(value, context));
                }
                return of(null);
            }));
        });
        isRequiredValidator(validator) && markForRequired(next);
        return next;
    };
}
