/**
 * Generate index files.
 * @function ci.worker.generateIndexFiles
 * @param {object} config - Task configuration.
 * @param {string[]} config.dirs - Directory names to generate index files.
 * @param {string[]} config.capitalizePatterns - File name pattern to exports with capitalized name.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var lib = require('../../lib'),
    string = lib.string,
    util = require('util'),
    path = require('path'),
    debug = require('./_debug'),
    generateIndex = require('./generate_index');

exports = module.exports = function (config, callback) {
    var capitalizePatterns = [].concat(config.capitalizePatterns || []),
        dirs = [].concat(config.dirs || []);
    require('async').series(
        dirs.map(function (dirname) {
            return function (callback) {
                var namespaces = dirname.split('/'),
                    overview = util.format('%s module.',
                        string.capitalize(namespaces.join(' ')));
                generateIndex({
                    dir: dirname,
                    doc: {
                        overview: overview,
                        namespace: namespaces.join('.')
                    },
                    capitalize: capitalizePatterns
                        .filter(function (pattern) {
                            return pattern.match(dirname)
                        })
                        .map(function (pattern) {
                            return path.relative(dirname, pattern);
                        })
                }, callback);
            };
        }),
        function (err) {
            callback(err);
        }
    );
};