/**
 * Install bower components.
 * @function task.worker.installBowerComponents
 * @param {object} config - Task configuration.s
 * @param {string} config.destDir - Destination directory.
 * @param {object} config.packages - Packages to install. Keys are package names, values are package versions.
 * @example
 *      installBowerComponents({
 *          jquery: '~2.1.0'
 *      });
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 */
var path = require('path'),
    debug = require('./_debug');
exports = module.exports = function (config, callback) {
    var bower = require('bower'),
        destDir = path.resolve(config.destDir),
        cwd = process.cwd();
    try {

        bower
            .commands
            .install(
            exports._packagesSeries(config.packages), {},
            {
                cwd: cwd,
                directory: path.relative(cwd, destDir)
            }
        )
            .on('log', function (data) {
                console.log([data.id, data.message].join(' '));
            })
            .on('end', function (results) {
                Object.keys(results).forEach(function (packageName) {
                    debug.didInstall(packageName, destDir);
                });
                callback(null);
            });
    } catch (e) {
        callback(e);
    }
};

exports._packagesSeries = function (data) {
    return Object.keys(data).map(function (name) {
        var version = data[name];
        return [name, version].join('#');
    });
};
