/**
 * Remove symbolic links if it's destination file does not exist.
 * @function ci.worker.cleanDeadSymlinks.
 * @param {object} config - Configuration object.
 * @param {string} [config.basedir='.'] - Directory to clean.
 * @param {function} callback - Callback when done.
 * @function
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    path = require('path'),
    debug = require('./_debug'),
    readdirRecursive = require('../../lib/file/readdir_recursive');

exports = module.exports = function (config, callback) {
    var async = require('async');
    var basedir = config.basedir || '.';
    readdirRecursive(basedir, function (err, filenames) {
        if (err) {
            callback(err);
            return;
        }
        async.parallel(
            filenames
                .map(function (filename) {
                    return path.resolve(basedir, filename);
                })
                .map(function (filename) {
                    return function (callback) {
                        fs.lstat(filename, function (err, stats) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            var isSymlink = stats.isSymbolicLink();
                            if (!isSymlink) {
                                callback(err);
                                return;
                            }
                            fs.exists(filename, function (eixsts) {
                                if (eixsts) {
                                    callback(null);
                                } else {
                                    fs.unlink(filename, function (err) {
                                        if (!err) {
                                            debug.cleanDeadLink(filename);
                                        }
                                        callback(err);
                                    });
                                }
                            });

                        });
                    }
                }),
            function (err) {
                callback(err);
            }
        )
    });
};