/**
 * Generate public locale files.
 * @function task.worker.generateClientsideLocaleFiles
 * @param {object} config - Work configuration.
 * @param {string} config.srcDir - Locale source directory name.
 * @param {string} config.destDir - Public directory name.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    debug = require('./_debug'),
    path = require('path'),
    file = require('../../lib/file'),
    writeReadonlyFile = file.writeReadonlyFile,
    loadHbsTmpl = file.loadHbsTmpl;

exports = module.exports = function (config, callback) {
    var async = require('async'),
        srcDir = path.resolve(config.srcDir),
        destDir = path.resolve(config.destDir);
    exports._loadPublicLocaleTmpl(function (err, tmpl) {
        if (err) {
            callback(err);
            return;
        }
        fs.readdir(srcDir, function (err, filenames) {
            if (err) {
                callback(err);
                return;
            }
            async.series(
                filenames
                    .filter(function (filename) {
                        return !filename.match(/^\./)
                    })
                    .filter(function (filename) {
                        return filename != 'index.js'
                    })
                    .map(function (filename) {
                        return path.resolve(srcDir, filename)
                    })
                    .map(function (src) {
                        return function (callback) {
                            var data = tmpl({
                                data: JSON.stringify(require(src), null, 4),
                                src: path.relative('.', src)
                            });
                            var dest = path.resolve(destDir, path.basename(src));
                            writeReadonlyFile(dest, data, function (err) {
                                if (!err) {
                                    debug.didCreateFile(dest);
                                }
                                callback(err);
                            });
                        }
                    }),
                function (err) {
                    callback(err);
                }
            )
        });
    });
};

exports._loadPublicLocaleTmpl = function (callback) {
    var filename = path.resolve(__dirname, '../../tmpl/js/public_locale.js.hbs');
    loadHbsTmpl(filename, callback);
};