'use strict';

var UtilArray = require('./UtilArray');

function filterDuplicates(includeNames) {
    var filtered = [];

    for (var i = 0; i < includeNames.length; i++) {
        var includeName = includeNames[i];
        if (!UtilArray.contains(filtered, includeName)) {
            filtered.push(includeName);
        }
    }

    return filtered;
}

function getIncludeNames(ruleFlow) {
    if (ruleFlow) {
        var includeNames = [];

        var exp = /[\t ]*[\#]include\s+\".*\"/mg;
        var syntax;
        while ((syntax = exp.exec(ruleFlow)) !== null) {
            if (syntax) {
                var exp2 = new RegExp("['\"](.*)['\"]");
                var includeName = exp2.exec(syntax)[1];
                includeNames.push(includeName);
            }
        }

        return includeNames;
    }

    return [];
};

module.exports = {
    getIncludeNames: function(ruleFlow) {
        var includeNames = getIncludeNames(ruleFlow);
        return [].concat(filterDuplicates(includeNames));
    },
    getDuplicateIncludes: function (ruleFlow) {
        var includeNames = getIncludeNames(ruleFlow);
        var filtered = [];

        for (var i = 0; i < includeNames.length; i++) {
            var includeName = includeNames[i];
            if (!UtilArray.contains(filtered, includeName)) {
                filtered.push(includeName);
            } else {
                return includeName;
            }
        }

        return null;
    }
};
