/**
 * Generate tasks index.js file.
 * @function ci.worker.generateCiTasksIndex
 * @param {object} config - Task configuration.
 * @param {string} config.dir - Tasks directory name.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    fs = require('fs'),
    lib = require('../../lib'),
    file = lib.file,
    string = lib.string,
    _loadLocalTmpl = require('./_load_local_tmpl'),
    _workerName = require('./_worker_name'),
    debug = require('./_debug');

exports = module.exports = function (config, callback) {
    var dirname = path.resolve(config.dir),
        dest = path.resolve(dirname, 'index.js');
    exports._loadTasksIndexTmpl(function (err, tmpl) {
        if (err) {
            callback(err);
            return;
        }
        exports._renderData(dirname, function (err, data) {
            if (err) {
                callback(err);
            }
            var content = tmpl(data);
            file.writeReadonlyFile(dest, content, function (err) {
                if (!err) {
                    debug.didCreateFile(dest);
                }
                callback(err);
            });
        });
    });
};

exports._loadTasksIndexTmpl = function (callback) {
    _loadLocalTmpl('js/ci_tasks_index.js.hbs', callback);
};

exports._renderData = function (dirname, callback) {
    fs.readdir(dirname, function (err, filenames) {
        if (err) {
            callback(err);
            return;
        }
        callback(null, {
            authorModule: _workerName.full(__filename),
            modules: filenames
                .filter(function (filename) {
                    return !filename.match(/^\./);
                })
                .filter(function (filename) {
                    return filename !== 'index.js';
                })
                .map(function (filename) {
                    var required = require(path.resolve(dirname, filename)),
                        basename = path.basename(filename, path.extname(filename));
                    return {
                        exportsName: string.camelize(basename),
                        requireName: './' + basename,
                        taskNames: Object.keys(required).filter(function (name) {
                            return !name.match(/^_/);
                        })
                    }
                })
        });
    });
}
;