var fs = require('fs'),
    path = require('path'),
    testResource = require('../../../test_resource'),
    rmdirRecursive = require('../../../../lib/file/rmdir_recursive');

exports['Remove a directory recursive'] = function (test) {
    testResource.prepareCleanWorkDirForTestFile(__filename, function (err, workDir) {
        fs.mkdir(path.resolve(workDir, 'foo'), function () {
            fs.writeFile(path.resolve(workDir, 'a.txt'), 'abc', function () {
                rmdirRecursive(workDir, function (err) {
                    test.ifError(err);
                    test.done();
                });
            });
        });
    });
};

exports['Handle errors.'] = function (test) {
    rmdirRecursive('/foo/bar/__not_exists', function (err) {
        test.ifError(err);
        testResource.prepareCleanWorkDirForTestFile(__filename, function (err, workDir) {
            var readdir = fs.readdir;
            fs.readdir = function (dirname, callback) {
                callback('Error');
            };
            rmdirRecursive(workDir, function (err) {
                test.ok(err);
                fs.readdir = readdir;
                var lstat = fs.lstat;
                fs.lstat = function (filename, callback) {
                    callback('Error');
                };
                fs.writeFile(workDir + '/foo.txt', function () {
                    rmdirRecursive(workDir, function (err) {
                        test.ok(err);
                        fs.lstat = lstat;
                        test.done();
                    });
                });
            });
        });
    });
};

exports['Handle errors on removing a directory.'] = function (test) {
    rmdirRecursive._rmdir('foo/bar/_not_exists', function (err) {
        test.ok(err);
        var readdir = fs.readdir;
        fs.readdir = function (dirname, callback) {
            callback('Error');
        };
        testResource.prepareCleanWorkDirForTestFile(__filename, function (err, workDir) {
            rmdirRecursive._rmdir(workDir, function (err) {
                test.ok(err);
                fs.readdir = readdir;
                test.done();
            });
        });

    });
};

exports['Remove a symlink dir.'] = function (test) {
    testResource.prepareCleanWorkDirForTestFile(__filename, function (err, workDir) {
        var linkSrcDir = path.resolve(workDir, 'src'),
            linkDestDir = path.resolve(workDir, 'dest');
        fs.mkdir(linkSrcDir, function () {
            fs.symlink(linkSrcDir, linkDestDir, function () {
                rmdirRecursive._rmdir(linkDestDir, function (err) {
                    test.ifError(err);
                    test.done();
                });
            });
        });
    });
};