/**
 * Pack an app as npm package.
 * @function ci.worker.packNpmPackage
 * @param {object} config - Task configuration.
 * @param {string} config.basedir - App dir to pack.
 * @param {function} callback - Callback when done.
 */
var path = require('path'),
    util = require('util'),
    format = util.format,
    spawn = require('child_process').spawn,
    debug = require('./_debug'),
    generatePackageJSON = require('./generate_package_json');

module.exports = function (config, callback) {
    var basedir = path.resolve(config.basedir);
    var packagePath = path.resolve(basedir, 'package.json');
    generatePackageJSON({
        src: path.resolve(basedir, 'Apemanfile.js'),
        dest: packagePath
    }, function (err) {
        if (err) {
            callback(err);
            return;
        }
        var data = require(packagePath),
            packedName = path.resolve(basedir, format('%s-%s.tgz', data.name, data.version));
        var npm = spawn('npm', ['pack'], {
            cwd: basedir
        });
        if(!config.silent)npm.stdout.pipe(process.stdout);
        npm.on('close', function () {
            debug.didCreateFile(packedName);
            callback(null, packedName);
        });
    });
};