console.log('Loading...');

var AWS = require('aws-sdk');
var s3Zip = require('s3-zip');


exports.handler = function (event, context) {
  console.log('event', event);

console.log('assigning vars...');

/*
  There is an issue between function and the structure of objects in S3.
  Objects in S3 are not grouped by package but in subfolders by type.
  So download in this code works for objects in a single sub-folder and
  NOT objects spread across subfolders.

*/

console.log('region: ' + event.region);
console.log('bucket: ' + event.bucket);
console.log('folder: ' + event.folder);
console.log('files: ' + event.files.toString());
console.log('zipFileName: ' + event.zipFileName);


var region = event.region;
var bucket = event.bucket;
var folder = event.folder;
var files = event.files;
var zipFileName = event.zipFileName;

  // Create body stream
  try {

    console.log('calling s3ZIP.archive...');

    var body = s3Zip.archive({ region: region, bucket: bucket}, folder, files);
    
    var zipParams = { params: { Bucket: bucket, Key: folder + zipFileName } };
    var zipFile = new AWS.S3(zipParams);
    
    var upload = zipFile.upload({ Body: body });
      upload.on('httpUploadProgress', function (evt) { console.log(evt); });
      upload.send(function (e, r) { 
        if (e) {
          var err = 'zipFile.upload error ' + e;
          console.log(err);          
          context.fail(err);
        } 
        console.log(r); 
        context.succeed(r);
      });

  } catch (e) {
    var err = 'catched error: ' + e;
    console.log(err);          
    context.fail(err);
  }
};