/**
 * Generate a html file from markdown.
 * @function task.worker.generateHtmlFromMarkdown
 * @param {object} config - Work configuration.
 * @param {string} config.src - Source markdown file path.
 * @param {string} config.dest - Destination html file path.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    util = require('util'),
    debug = require('./_debug'),
    fs = require('fs'),
    lib = require('../../lib'),
    string = lib.string,
    file = lib.file,
    underscorize = string.underscorize,
    forceUnlink = file.forceUnlink,
    html = lib.html,
    markdown2html = html.markdown2html;

exports = module.exports = function (config, callback) {
    var src = exports._resolveAll(config.src),
        dest = exports._resolveAll(config.dest);
    require('async')
        .series(
            src.map(function (src, i) {
                return function (callback) {
                    exports._convert(src, dest[i] || dest[0], callback);
                }
            }),
            callback
        );

};


exports._resolveAll = function (filename) {
    return [].concat(filename || []).map(function (filename) {
        return path.resolve(filename);
    });
};

exports._convert = function (src, dest, callback) {
    dest = util.format(dest, underscorize(path.basename(src, path.extname(src)).toLowerCase())
        .replace(/_/g, '-')).replace(/\-\-/g, '-').replace(/\-\./g, '.');
    forceUnlink(dest, function (err) {
        if (err) {
            callback(err);
            return;
        }
        markdown2html(src, dest, function (err) {
            if (err) {
                callback(err);
                return;
            }
            fs.chmod(dest, '444', function (err) {
                if (!err) {
                    debug.didCreateFile(dest);
                }
                callback(err);
            });
        });
    });
};