/**
 * Generate index test file.
 * @function ci.worker.generateIndexTest
 * @param {object} config - Task configuration.
 * @param {string} config.srcDir - Source directory name.
 * @param {string} config.destDir - Destination directory name.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 */
var apeman = require('apeman'),
    fs = require('fs'),
    path = require('path'),
    string = require('../../lib/string'),
    file = require('../../lib/file'),
    object = require('../../lib/object'),
    camelize = string.camelize,
    mkdirP = file.mkdirP,
    debug = require('./_debug'),
    writeReadonlyFile = file.writeReadonlyFile,
    _loadLocalTmpl = require('./_load_local_tmpl');

exports = module.exports = function (config, callback) {
    var destRootDir = path.resolve(config.destDir),
        srcDir = [].concat(config.srcDir || []).map(function (srcDir) {
            return path.resolve(srcDir);
        }),
        baseDir = apeman.currentProject.basedir;
    exports._loadIndexJsTmpl(function (err, tmpl) {
        if (err) {
            callback(err);
            return;
        }
        require('async').series(
            srcDir.map(function (srcDir) {
                return function (callback) {
                    var index = require('./' + path.relative(__dirname, srcDir)),
                        destDir = path.resolve(destRootDir, path.relative(baseDir, srcDir));
                    var content = tmpl({
                        modulePath: path.relative(destDir, srcDir),
                        keys: Object.keys(index)
                    });
                    var dest = path.resolve(destDir, 'index_test.js');
                    mkdirP(path.dirname(dest), function (err) {
                        if (err) {
                            callback(err);
                            return;
                        }
                        writeReadonlyFile(dest, content, function (err) {
                            if (!err) {
                                debug.didCreateFile(dest);
                            }
                            callback(err);
                        });
                    });
                };
            }),
            function (err) {
                callback(err)
            }
        );
    });
};

/**
 * Load the index test js template.
 * @param {function} callback - Callback when done.
 * @protected
 * @ignore
 */
exports._loadIndexJsTmpl = function (callback) {
    _loadLocalTmpl('js/index_test.js.hbs', callback);
};

