/**
 * Generate visualized json files.
 * @function ci.worker.generateVisualizeJsonFiles
 * @param {object} config - Task configuration
 * @param {string} config.srcPattern - Source file name pattern.
 * @param {string} config.destFormat - Destination file name pattern.
 * @example
 *  generateVisualizeJsonFiles({
 *      srcPattern: 'foo/bar/*-config.js',
 *      // "%s" will be replace with base name of each src file name.
 *      destFormat: 'foo/bar/.%s-visual.js'
 *  })
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    util = require('util'),
    lib = require('../../lib'),
    file = lib.file,
    debug = require('./_debug'),
    generateConfigDataJson = require('./generate_config_data_json');

exports = module.exports = function (config, callback) {
    var destFormat = path.resolve(config.destFormat);
    file.expandGlob(config.srcPattern, function (err, src) {
        if (err) {
            callback(err);
            return;
        }
        require('async').series(
            src.map(function (src) {
                return function (callback) {
                    var dest = exports._formatDest(destFormat, src);
                    file.mkdirP(path.dirname(dest), function (err) {
                        if (err) {
                            callback(err);
                            return;
                        }
                        generateConfigDataJson({
                            src: src,
                            dest: dest
                        }, callback);
                    });
                }
            }),
            function (err) {
                callback(err);
            }
        )
    });
};

exports._formatDest = function (foramt, src) {
    var basename = path.basename(src, path.extname(src));
    return util.format(foramt, basename);
};