/**
 * @function task.worker._convertDirectory
 * @param {object} config
 * @param {string} config.srcDir - Source jade directory.
 * @param {string} config.ignore - Ignore  jade pattern. Glob.
 * @param {string} config.pattern - Source jade file pattern. Glob.
 * @param {string} config.destDir - Destination html directory.
 * @param {function} config.fileNameConverter - Function to convert file name.
 * @param {function} config.fileContentConverter - Function to convert file content.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */

var path = require('path'),
    fs = require('fs'),
    debug = require('./_debug'),
    file = require('../../lib/file'),
    mkdirP = file.mkdirP,
    _expandGlobUnlessIgnored = require('./_expand_glob_unless_ignored');

exports = module.exports = function (config, callback) {
    var async = require('async'),
        srcDir = path.resolve(config.srcDir),
        destDir = path.resolve(config.destDir),
        fileNameConverter = config.fileNameConverter,
        fileContentConverter = config.fileContentConverter,
        ignore = config.ignore && [].concat(config.ignore).map(function (ignore) {
            return path.resolve(srcDir, ignore)
        }),
        src = path.resolve(srcDir, config.pattern || '*');
    _expandGlobUnlessIgnored(src, ignore, function (err, filenames) {
        if (err) {
            callback(err);
            return;
        }
        async.series(
            filenames
                .map(function (src) {
                    var filename = path.relative(srcDir, src),
                        dest = path.resolve(destDir, fileNameConverter(filename));
                    return {
                        src: src,
                        dest: dest
                    }
                })
                .map(function (data) {
                    return function (callback) {
                        var src = data.src, dest = data.dest;
                        mkdirP(path.dirname(dest), function (err) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            fileContentConverter(src, dest, callback);
                        });
                    }
                }),
            function (err) {
                callback(err)
            }
        )
    });
};