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

exports['Write a read only file'] = function (test) {
    testResource.prepareCleanWorkDirForTestFile(__filename, function (err, workDir) {
        var filename = path.resolve(workDir, 'foo.txt');
        writeReadonlyFile(filename, 'foo', function (err) {
            test.ifError(err);
            if (fs.existsSync(filename)) fs.chmodSync(filename, '777');
            writeReadonlyFile(filename, 'foo', function (err) {
                test.ifError(err);
                test.done();
            });
        });
    });
};

exports['Handle errors.'] = function (test) {
    var _forceUnlink = writeReadonlyFile._forceUnlink;
    writeReadonlyFile._forceUnlink = function (filename, callback) {
        callback(new Error('foo'));
    };
    writeReadonlyFile('bar', '', function (err) {
        test.ok(err);
        writeReadonlyFile._forceUnlink = function (filename, callback) {
            callback(null);
        };
        var _writeFile = writeReadonlyFile._writeFile;
        writeReadonlyFile._writeFile = function (filename, content, callback) {
            callback(new Error('baz'));
        };
        writeReadonlyFile('quz', '', function (err) {
            test.ok(err);
            writeReadonlyFile._forceUnlink = _forceUnlink;
            writeReadonlyFile._writeFile = _writeFile;
            test.done();
        });
    });
};