/**
 * Compile a jade file.
 * @function lib.compile.precompileJadeFile
 * @see {@link http://jade-lang.com/reference/ | jade}
 * @param {string} src - Source jade file.
 * @param {string} dest - Destination html file.
 * @param {object} data - Render data.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    path = require('path'),
    precompileJadeString = require('./precompile_jade_string'),
    file = require('../file'),
    minify = require('../minify'),
    format = require('util').format,
    minifyJsString = minify.minifyJsString,
    mkdirP = file.mkdirP,
    writeReadonlyFile = file.writeReadonlyFile;

module.exports = function (src, dest, callback) {
    fs.readFile(src, function (err, buffer) {
        if (err) {
            callback(err);
            return;
        }
        var options = {};
        options.filename = src;
        precompileJadeString(buffer.toString(), options, function (err, precompiled) {

            if (err) {
                callback(err);
                return;
            }
            mkdirP(path.dirname(dest), function (err) {
                if (err) {
                    callback(err);
                    return;
                }
                var script = format('var jade=require("jade").runtime;module.exports=%s', precompiled.toString());
                minifyJsString(script, function (err, minified) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    writeReadonlyFile(dest, minified, function (err) {
                        callback(err);
                    });
                });
            });
        });
    });
};