var _ = require('lodash');

function codeMatches(candidate, code){
    var codeValue = code.code;
    if (_.isRegExp(codeValue)){
        delete code.code;
        var matchWithoutCode = _.matches(code)(candidate);
        code.code = codeValue;
        if (!matchWithoutCode){
            return false;
        }
        return candidate.code.match(codeValue) != null;
    }
    else {
        return _.matches(code)(candidate);
    }
}

var assert = {
    includesCode: function(code){
        if (!code) {
            throw new Error('code undefined')
        }
        return function(coding){
            return coding.reduce(function (prev, candidate) {
                if (prev) return prev;

                return codeMatches(candidate, code)
            }, false);
        }
    },
    includesCodeFromSet: function(codes){
        if (!codes) {
            throw new Error('codes undefined')
        }

        codes = Array.isArray(codes) ? codes : [codes];

        return function(coding){
            return coding.reduce(function (prev, candidate) {
                if (prev) return prev;

                return codes.reduce(function(prev, code){
                    if (prev) return prev;

                    return codeMatches(candidate, code);
                }, false);
            }, false);
        }
    }
};

module.exports = assert;