/**
 * Generate scaffold file.
 * @function task.worker.generateScaffold
 * @param {object} config - Task Configuration
 * @param {string} config.tmplName - Template file.
 * @param {string} config.destDir - Destination directory.
 * @param {string} config.destNameFormat - Destination file name format.
 * @param {string} config.settingFile - Setting file name.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 */

var path = require('path'),
    util = require('util'),
    fs = require('fs'),
    _scaffoldData = require('./_scaffold_data'),
    _writeFileUnlessExists = require('./_write_file_unless_exists'),
    _loadLocalTmpl = require('./_load_local_tmpl'),
    debug = require('./_debug');

module.exports = function (config, callback) {
    var setting = require(path.resolve(config.settingFile)),
        destFileNameFormat = config.destNameFormat,
        destDir = path.resolve(config.destDir);
    _loadLocalTmpl(config.tmplName, function (err, tmpl) {
        if (err) {
            callback(err);
            return;
        }
        require('async').series(
            setting.modelNames.map(function (modelName) {
                var data = _scaffoldData(modelName);
                return function (callback) {
                    var dest = path.resolve(
                        destDir,
                        util.format(destFileNameFormat, data.snakeName)
                    );
                    var content = tmpl(data);
                    _writeFileUnlessExists(dest, content, function (err) {
                        if (!err) {
                            debug.didCreateFile(dest);
                        }
                        callback(err);
                    });
                }
            }), function (err) {
                callback(err);
            }
        );
    });
};