/**
 * Post coverage data to coveralls.
 * @see {@link http://coveralls.io | coveralls}
 * @function ci.worker.reportToCoveralls
 * @param {object} config - Task configuration.
 * @param {string[]} config.files - nodeunit test files.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 */
var path = require('path'),
    childProcess = require('child_process'),
    lib = require('../../lib'),
    file = lib.file,
    expandGlob = file.expandGlob,
    spawn = childProcess.spawn;

exports = module.exports = function (config, callback) {
    expandGlob(config.files, function (err, testFiles) {
        if (err) {
            callback(err);
            return;
        }

        var coverallsBin = exports._coverallsBin,
            nodeunitBin = exports._nodeunitBin;
        var nodeunit = spawn(nodeunitBin, ['--reporter=lcov'].concat(testFiles), {
            env: process.env
        });

        var coveralls = spawn(coverallsBin);
        nodeunit.stdout.pipe(coveralls.stdin);
        nodeunit.stderr.pipe(coveralls.stdin);
        coveralls.stdout.pipe(process.stdout);
        coveralls.stderr.pipe(process.stderr);


        function done(err) {
            setTimeout(function () {
                callback && callback(err || null);
                callback = null;
            }, 10);
        }

        coveralls.on('error', done);
        nodeunit.on('error', done);

        coveralls.on('exit', function () {
            done(null);
        });
        nodeunit.on('exit', function () {
            done(null);
        });
    });
};

exports._coverallsBin = path.resolve(require.resolve('coveralls'), '../bin/coveralls.js');
exports._nodeunitBin = path.resolve(require.resolve('nodeunit'), '../bin/nodeunit');