/**
 * Minify file(s);
 * @function lib.minify._minifyFile
 * @param {string|string[]} src - File name to minify.
 * @param {string} dest - Destination file name.
 * @param {function} minify - Minify function.
 * @param {function} callback - Callback when done.
 * @protected
 * @ignore
 * @author Taka Okunishi
 *
 */

var path = require('path'),
    fs = require('fs'),
    file = require('../file'),
    forceUnlink = file.forceUnlink;

module.exports = function (src, dest, minifier, callback) {
    var async = require('async');
    dest = path.resolve(dest);
    forceUnlink(dest, function (err) {
        if (err) {
            callback(err);
            return;
        }
        async.parallel(
            [].concat(src)
                .map(function (src) {
                    return path.resolve(src)
                })
                .map(function (src) {
                    return function (callback) {
                        fs.readFile(src, function (err, buffer) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            minifier(buffer.toString(), function (err, minified) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                fs.appendFile(dest, minified, function (err) {
                                    callback(err);
                                });
                            });
                        });
                    }
                }),
            function (err) {
                if (err) {
                    callback && callback(err);
                    return;
                }
                fs.exists(dest, function (exists) {
                    if (!exists) {
                        callback && callback(null);
                        return;
                    }
                    fs.chmod(dest, '444', function (err) {

                        callback && callback(err);
                    });
                });
            }
        );
    });
};