/**
 * Generate task define helper.
 * @module ci.worker.generateTaskDefineHelper
 * @param {object} config - Task configuration
 * @param {string} config.workerDir - Worker file directory.
 * @param {string} config.dest - Destination file name
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    lib = require('../../lib'),
    file = lib.file,
    string = lib.string,
    _workerName = require('./_worker_name'),
    _loadLocalTmpl = require('./_load_local_tmpl'),
    debug = require('./_debug');

exports = module.exports = function (config, callback) {
    var dest = path.resolve(config.dest),
        workerDir = path.resolve(config.workerDir),
        testDest = config.testDest && path.resolve(config.testDest);
    exports._loadTaskDefineHelperTmpl(function (err, tmpl) {
        if (err) {
            callback(err);
            return;
        }
        file.readdirRecursive(workerDir, function (err, workerFiles) {
            if (err) {
                callback(err);
                return;
            }
            var workerModule = require(workerDir);
            var data = {
                authorModule: _workerName.full(__filename),
                workerPath: 'ci/worker',
                workers: Object.keys(workerModule).map(function (key) {
                    return {
                        name: key,
                        readableName: string.underscorize(key).split(/_/)
                    }
                })

            };

            var content = tmpl(data);
            file.writeReadonlyFile(dest, content, function (err) {
                if (!err) {
                    debug.didCreateFile(dest);
                }
                if (testDest) {
                    data.modulePath = path.relative(path.dirname(testDest), dest);
                    data.moduleName = string.camelize(path.basename(dest, '.js'));
                    exports._writeTestFile(testDest, data, callback);
                } else {
                    callback(err);
                }
            });
        });
    });
};

exports._writeTestFile = function (dest, data, callback) {
    exports._loadTaskDefineHelperTestTmpl(function (err, tmpl) {
        require('./_write_unit_test_file')(dest, tmpl, data, callback);
    });
};


exports._shouldIgnore = function (filename) {
    var basename = path.basename(filename);
    if (basename === 'index.js') return true;
    return !!basename.match(/^\./);
};

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

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