var testResource = require('../../../test_resource'),
    fs = require('fs'),
    mockInjector = require('../../../mock_injector'),
    cleanDeadSymlinks = require('../../../../ci/worker/clean_dead_symlinks');

exports.setUp = function (done) {
    process.env.CI_LOG_DISABLED = true;
    done();
};
exports.tearDown = function (done) {
    process.env.CI_LOG_DISABLED = false;
    mockInjector.restoreAll();
    done();
};


exports['Clean dead sym links'] = function (test) {
    testResource.prepareCleanWorkDirForTestFile(__filename, function (err, workDir) {
        var file01 = testResource.resolveWorkFile(workDir, 'file01.txt'),
            link01 = testResource.resolveWorkFile(workDir, 'file01_link');
        fs.writeFile(file01, 'foo', function () {
            fs.symlink(file01, link01, function () {
                fs.unlink(file01, function () {
                    cleanDeadSymlinks({
                        basedir: workDir
                    }, function (err) {
                        test.ifError(err);
                        test.done();
                    });
                });
            });
        });
    });
};

exports['Handle error.'] = function (test) {
    cleanDeadSymlinks({
        basedir: '/foo/bar/not_exists'
    }, function (err) {
        test.ok(err);
        testResource.prepareCleanWorkDirForTestFile(__filename, function (err, workDir) {
            mockInjector.inject(fs, 'lstat', function (f, callback) {
                callback(new Error('lstat mock error'));
            });
            var file01 = testResource.resolveWorkFile(workDir, 'file01.txt'),
                link01 = testResource.resolveWorkFile(workDir, 'file01_link');
            fs.writeFile(file01, 'foo', function () {
                fs.symlink(file01, link01, function () {
                    cleanDeadSymlinks({
                        basedir: workDir
                    }, function (err) {
                        test.ok(err);
                        mockInjector.restore();
                        test.done();
                    });
                });
            });
        });
    });
};