/**
 * Unlink forcefully.
 * @function lib.file.forceUnlink
 * @param {string} filename - File name to unlink.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    path = require('path');

exports = module.exports = function (filename, callback) {
    fs.exists(filename, function (exists) {
        if (!exists) {
            exports._cleanDeadSymlink(filename, callback);
            return;
        }
        fs.lstat(filename, function (err, stat) {
            if (err) {
                callback(err);
                return;
            }
            var isSymlink = stat.isSymbolicLink();
            if (isSymlink) {
                fs.unlink(filename, function (err) {
                    callback(err);
                });
            } else {
                fs.chmod(filename, '777', function (err) {
                    if (err) {
                        callback(err);
                    } else {
                        fs.stat(filename, function (err, stats) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            if (stats.isDirectory()) {
                                require('./rmdir_recursive')(filename, function (err) {
                                    callback(err);
                                });
                            } else {

                                fs.unlink(filename, function (err) {
                                    callback(err);
                                });
                            }
                        });
                    }
                });
            }
        });
    });
};

exports._cleanDeadSymlink = function (filename, callback) {
    var dirname = path.dirname(filename);
    fs.exists(dirname, function (exists) {
        if (exists) {
            fs.readdir(dirname, function (err, filenames) {
                //If the file is dead symlink, fs.exists gives false, but listed when fs.readdir called.
                var deadSymlink = filenames.indexOf(path.basename(filename)) !== -1;
                if (deadSymlink) {
                    fs.unlink(filename, function (err) {
                        callback(err);
                    });
                } else {
                    callback(null);
                }
            });
        } else {
            callback(null);
        }
    });
};
