import { __assign } from "tslib";
import { isAsyncValidator, createAsyncValidator, } from '../validate';
import { of, from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { markForRequired, isRequiredValidator } from '../validators';
function withMessage(maybeError, messagenerator, ctx) {
    return maybeError && __assign(__assign({}, maybeError), { message: messagenerator(ctx) });
}
export function message(messagenerator) {
    return function (validator) {
        var next = isAsyncValidator(validator)
            ? createAsyncValidator(function (value, context) {
                var result = validator.validator(value, context);
                return (result &&
                    from(result).pipe(switchMap(function (maybeError) {
                        return of(withMessage(maybeError, messagenerator, context));
                    })));
            })
            : function (value, context) {
                return withMessage(validator(value, context), messagenerator, context);
            };
        isRequiredValidator(validator) && markForRequired(next);
        return next;
    };
}
