/**
 * Remove a directory recursive.
 * @function lib.file.rmdirRecursive
 * @param {string} dirname - Directory path to remove.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    path = require('path'),
    forceUnlink = require('./force_unlink');

exports = module.exports = function (dirname, callback) {
    if (!callback) callback = new Function;
    var async = require('async');
    fs.exists(dirname, function (exists) {
        if (!exists) {
            callback(null);
            return;
        }
        fs.readdir(dirname, function (err, filenames) {
            if (err) {
                callback(err);
                return;
            }
            async.parallel(
                filenames
                    .map(function (filename) {
                        return path.resolve(dirname, filename);
                    })
                    .map(function (filename) {
                        return function (callback) {
                            fs.lstat(filename, function (err, lstats) {
                                if (err) {
                                    callback(err);
                                } else {
                                    if (lstats.isDirectory()) {
                                        exports._rmdir(filename, callback);
                                    } else {
                                        if (lstats.isSymbolicLink()) {
                                            fs.unlink(filename, callback);
                                        } else {
                                            forceUnlink(filename, callback);
                                        }
                                    }
                                }
                            });
                        };
                    }),
                function (err) {
                    callback(err);
                }
            );

        });
    });
};
exports._rmdir = function (dirname, callback) {
    fs.lstat(dirname, function (err, lstats) {
        if (err) {
            callback(err);
            return;
        }
        if (lstats.isSymbolicLink()) {
            fs.unlink(dirname, callback);
            return;
        }
        exports(dirname, function (err) {
            if (err) {
                callback(err);
            } else {
                fs.rmdir(dirname, function (err) {
                    callback(err);
                });
            }
        });
    });
};