/**
 * Generate dot-data json file.
 * @function task.worker.generateDataJson
 * @param {object} config - Work configuration.
 * @param {string} config.src - Source file names. Glob.
 * @param {string} config.ignore - Ignore  filename pattern. Glob.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    fs = require('fs'),
    file = require('../../lib/file'),
    writeReadonlyFile = file.writeReadonlyFile,
    debug = require('./_debug'),
    _basenameWithoutExt = require('./_basename_without_ext'),
    _expandGlobUnlessIgnored = require('./_expand_glob_unless_ignored'),
    format = require('util').format;

exports = module.exports = function (config, callback) {
    var async = require('async'),
        ignore = config.ignore && path.resolve(config.ignore),
        src = path.resolve(config.src);
    _expandGlobUnlessIgnored(src, ignore, function (err, filenames) {
        if (err) {
            callback(err);
            return;
        }
        async.parallel(
            filenames
                .map(function (src) {
                    return function (callback) {
                        var dest = exports._nameDotDataJson(src),
                            content = JSON.stringify(require(src), null, 4);
                        writeReadonlyFile(dest, content, function (err) {
                            if (!err) {
                                debug.didCreateFile(dest);
                            }
                            callback(err);
                        });
                    }
                }),
            function (err) {
                callback(err);
            }
        );
    });
};

exports._nameDotDataJson = function (src) {
    var dirname = path.dirname(src),
        basename = _basenameWithoutExt(src);
    return path.resolve(dirname, format('.%s-data.json', basename));
};