import _ from 'lodash';

export function validate(validatorsMap) {
    return new Promise((resolve, reject) => {
        let result = Promise.resolve();
        let errors = {};

        // iterate by all keys except null values
        _.forOwn(_.omitBy(validatorsMap, _.isNull), (validator, key) => {
            result = result.then(() => {
                return validator.catch(error => {
                    errors[key] = error;
                    return Promise.resolve();
                });
            });
        });

        result.then(() => {
            if (_.isEmpty(errors)) {
                resolve();
            } else {
                reject(errors); //FIXME Promise rejected with non-Error
            }
        });
    });
}

export function stripErrors(errors) {
    return _.reduce(
        errors,
        (acc, errorDetails, errorFieldName) => {
            if (_.isString(errorDetails.message)) {
                acc[errorFieldName] = errorDetails.message;
            } else {
                acc[errorFieldName] = stripErrors(errorDetails);
            }

            return acc;
        },
        {}
    );
}
