/*jshint node:true*/
'use strict';
var Q = require('q'),
	async = require('async'),
	fetchDropletCmd = require('./fetch-droplet');

/**
 *
 * @param {Speedboat} speedboat
 * @returns {Function}
 */
module.exports = function (speedboat, _fetchDropletCmd_) {
	var DEFAULT_DIR = '/opt/app';

	fetchDropletCmd = _fetchDropletCmd_ || fetchDropletCmd;

	return function runNpmCommand (options, cwd) {
		var fetchDroplet = fetchDropletCmd(speedboat),
			deferred = Q.defer(),
			promise = deferred.promise,
			dropletName = options.subdomain + '.' + options.configObject.hostname,
			cmdOptions = '';

		cwd = cwd || DEFAULT_DIR;

		if (options.command === 'install') {
			cmdOptions += ' --unsafe-perm';
		}

		fetchDroplet(dropletName)
			.then(function (droplet) {
				if (!droplet) {
					throw new Error('Unable to retrieve droplet by name: ' + dropletName);
				}
				
				async.series([
					
					speedboat.plot(droplet.id, [
						'cd ' + cwd + ';',
						'npm run-script ' + options.command + cmdOptions
					].join(' '))

				], function (err, results) {
					if (err) {
						return deferred.reject(err);
					}
					deferred.resolve(results);
				});
			})
			.fail(function (err) {
				deferred.reject(err);
			});

		return promise;
	};
};
@@ -587,10 +587,10 @@
 s = 
-''
+%5B%5D
 ;%0A%0A%09
@@ -673,14 +673,15 @@
 ions
- += ' 
+.push('
 --un
@@ -690,16 +690,17 @@
 fe-perm'
+)
 ;%0A%09%09%7D%0A%0A%09
@@ -897,69 +897,242 @@
 %09%09%09%09
-speedboat.plot(droplet.id, %5B%0A%09%09%09%09%09%09'cd ' + cwd + ';',%0A%09%09%09%09%09%09'
+// Make the cwd directory if it doesn't exist (prevents errors)%0A%09%09%09%09%09// then change into it and run custom command%0A%09%09%09%09%09speedboat.plot(droplet.id, %5B%0A%09%09%09%09%09%09'mkdir ' + cwd + ';',%0A%09%09%09%09%09%09'cd ' + cwd + ';',%0A%09%09%09%09%09%09'%5B -f %22package.json%22 %5D && 
 npm 
@@ -1163,16 +1163,22 @@
 ommand +
+ ' ' +
  cmdOpti
@@ -1180,16 +1180,26 @@
 dOptions
+.join(' ')
 %0A%09%09%09%09%09%5D.

Check for existance of package.json before running command