'use strict';

var method = require('./../method');
var assign = require('lodash.assign');
var AWS = require('aws-sdk');
var fs = require('fs');

/**
 * @memberof jobs
 * @method artifactsGet
 * @description Get the artifacts files for the job with the given id.  The name of a particular file,
 * or directory can be spefified, and can include a wildcard character at the end, e.g., "myfiles"*.
 * If no specifc file or directory is specified all artifact files will be retrieved.
 * This action can only be performed by the user who owns the job, or in the case of
 * a team, the team administrator.
 * @param {object} params - Artifacts get parameters
 * @param {string} params.jobId - Id of the job to get artifacts for
 * @param {string} [params.files] - Optional; if getting only certian files, a file pattern to match against
 * @param {function} cb - Node-style error-first callback function
 * @returns one or more artifact files
 * @example
 * paperspace.jobs.artifactsGet({
 *   jobId: 'j123abc',
 *   files: 'myfiles*' // optional
 * }, function(err, resp) {
 *   // handle error or http response
 * });
 * @example
 * $ paperspace jobs artifactsGet \
 *     --jobId "j123abc" \
 *     --files "myfiles*"
 * @example
 * # HTTP request:
 * https://api.paperspace.io
 * GET /jobs/artifactsGet?jobId=j123abc&files=myfiles*
 * x-api-key: 1ba4f98e7c0...
 * # Returns 200 on success
 */

function artifactsGet(params, cb) {
	return method(artifactsGet, params, function artifactsGetCb(err, data) {
		if (!params.files || !params.files.length) return console.log('Error: files parameter currently required');
		if (params.files.endsWith('*')) return console.log('Error: wildcards not currently supported');
		var fileName = params.files;

		// XXX TODO warn if overwriting an existing file, prompt to overwrite?
		// XXX TODO catch exceptions from pipe, return as objects in api mode, or error message in cli module
		// XXX TODO add progress per file
		// XXX TODO support wildcards
		// XXX TODO clean up empty file on error
		// XXX TODO make sure sts and s3 versions are correct

		AWS.config.update({
			accessKeyId: data.body.Credentials.AccessKeyId,
      secretAccessKey: data.body.Credentials.SecretAccessKey,
      sessionToken: data.body.Credentials.SessionToken,
		});
		var s3 = new AWS.S3();
		var options = {
				Bucket: data.body.bucket,
				Key: data.body.folder + '/' + fileName,
		};
		var file = fs.createWriteStream(fileName);
		var fileStream = s3.getObject(options).createReadStream();
		console.log('Downloading ' + fileName);
		fileStream.pipe(file);
		console.log('Download complete');
	});
}

assign(artifactsGet, {
	auth: true,
	group: 'jobs',
	name: 'artifactsGet',
	method: 'get',
	route: '/jobs/artifactsGet',
	requires: {
		jobId: 'string',
		files: 'string',
	},
	returns: {},
});

module.exports = artifactsGet;

@@ -1427,83 +1427,8 @@
 ) %7B%0A
-%09return method(artifactsGet, params, function artifactsGetCb(err, data) %7B%0A%09
 %09if 
@@ -1532,17 +1532,16 @@
 ired');%0A
-%09
 %09if (par
@@ -1629,16 +1629,90 @@
 rted');%0A
+%09return method(artifactsGet, params, function artifactsGetCb(err, data) %7B%0A
 %09%09var fi
@@ -2052,39 +2052,533 @@
 re s
-ts and s3 versions are correct%0A
+3 version is correct%0A%09%09// XXX TODO aws creds cache%0A%09%09// XXX TODO fully shadow local aws creds%0A%0A%09%09if (!data.body %7C%7C !data.body.Credentials) %7B%0A%09%09%09var err = %7B error: 'Error: no credentials for artifacts folder.' %7D;%0A%09%09%09console.log(err.error);%0A%09%09%09return cb(err);%0A%09%09%7D%0A%09%09if (!data.body.bucket) %7B%0A%09%09%09var err = %7B error: 'Error: no artifacts bucket.' %7D;%0A%09%09%09console.log(err.error);%0A%09%09%09return cb(err);%0A%09%09%7D%0A%09%09if (!data.body.folder) %7B%0A%09%09%09var err = %7B error: 'Error: no artifacts folder.' %7D;%0A%09%09%09console.log(err.error);%0A%09%09%09return cb(err);%0A%09%09%7D
 %0A%09%09A

update artifactsGit result checks