/**
 * Generate scaffold files.
 * @function ci.worker.generateScaffoldFiles
 * @param {object} config - Task configuration
 * @param {string} config.tmplFile - Template file name.
 * @param {string} [config.data={}] - Data to render.
 * @param {string} config.destFormat - Destination file name format.
 * @param {string} config.names - Names to scaffold.
 * @param {function} callback - Callback when done.
 * @example
 *      generateScaffoldFiles({
 *          tmplFile: 'foo.hbs',
 *          dest: 'bar/%s.js'
 *          names: ['bar', 'baz']
 *      })
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    fs = require('fs'),
    util = require('util'),
    lib = require('../../lib'),
    object = lib.object,
    debug = require('./_debug'),
    string = lib.string,
    file = lib.file,
    _workerName = require('./_worker_name');

exports = module.exports = function (config, callback) {
    var tmplFile = path.resolve(config.tmplFile),
        destFormat = path.resolve(config.destFormat),
        names = [].concat(config.names || []);
    file.loadHbsTmpl(tmplFile, function (err, tmpl) {
        if (err) {
            callback(err);
            return;
        }
        require('async').series(
            names.map(function (name) {
                return function (callback) {
                    var data = exports._renderData(name, config.data || {}),
                        dest = util.format(destFormat, data.snake_name);
                    fs.exists(dest, function (exists) {
                        if (exists) {
                            callback(null);
                            return;
                        }
                        var content = tmpl(data);
                        fs.writeFile(dest, content, function (err) {
                            if (!err) {
                                debug.didCreateFile(dest);
                            }
                            callback();
                        });
                    });
                }
            }),
            function (err) {
                callback(err);
            }
        );
    });
};

exports._renderData = function (name, data) {
    var _newRenderData = require('./_new_render_data');
    name = string.underscorize(name);
    return _newRenderData(object.copy({
        authorModule: _workerName.full(__filename),
        snake_name: string.underscorize(name),
        SNAKE_NAME: name.toUpperCase(),
        SentenceName: string.capitalize(name).replace(/_/g, ' '),
        hyphenName: name.replace(/_/g, '-'),
        camelName: string.camelize(name),
        CamelName: string.camelize(name, true),
        get name() {
            return this.camelName;
        }
    }, data || {}));
};