/**
 * Generate basename links.
 * No matter how deep target files are, link file name put direct under the destination directory.
 * @function task.worker.generateBasenameLinks
 * @param {object} config - Work configuration.
 * @param {string} config.src - Source files with glob patterns.
 * @param {string} config.linkDir - Directory to create links.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    file = require('../../lib/file'),
    forceUnlink = file.forceUnlink,
    mkdirP = file.mkdirP,
    expandGlob = file.expandGlob,
    relativeSymlink = file.relativeSymlink,
    debug = require('./_debug');

module.exports = function (config, callback) {
    var async = require('async'),
        src = path.resolve(config.src),
        linkDir = path.resolve(config.linkDir);
    expandGlob(src, function (err, filenames) {
        if (err) {
            callback(err);
            return;
        }
        async.series(
            filenames
                .map(function (filename) {
                    return function (callback) {
                        var linkName = path.resolve(linkDir, path.basename(filename));
                        forceUnlink(linkName, function () {
                            mkdirP(path.dirname(linkName), function (err) {
                                if (err) {
                                    callback(err);
                                    return;
                                }
                                relativeSymlink(filename, linkName, function (err) {
                                    if (!err) {
                                        debug.didCreateLink(linkName, filename);
                                    }
                                    callback(err);
                                });
                            });
                        });
                    }
                }),
            function (err) {
                callback(err);
            }
        )
    });
};