/*
	Licensed Material - Property of IBM

	(C) Copyright 2015,2016 IBM Corp.

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/


'use strict';

//private modules
var errors = require('mdo-errors');
//public modules
var archiver = require('archiver');
var fs = require('fs');
var log = require('npmlog');
var path = require('path');
var q = require('q');
/** Creates a .zip file from a target directory
//
// @param sourceDir - target directory to zip
// @param destDir   - directory in which to place the .zip file
// @param filename  - name of .zip file to create
**/
module.exports = function createZip(sourceDir, destDir, filename){
	var d = q.defer();

    log.silly('createZip', 'creating zip file:  srcDir = '+sourceDir+'; destDir = '+destDir+'; filename = '+filename);

	// Open archive file
	var outputpath  = path.join(destDir, filename);
	var output = fs.createWriteStream(outputpath, {'flags': 'w'});  // Overwrite existing

    // Create and configure a .zip archiver
	var archive = archiver('zip');

	output.on('finish', function() {
        log.silly('createZip', 'archive complete');
		d.resolve();
	});

	archive.on('error', function(err) {
		log.verbose('createZip', 'Failure creating archive: '+err+' '+JSON.stringify(err));
		var creatingArchiveErr = errors.getError('FAILURECREATINGARCHIVE');
		d.reject(creatingArchiveErr);
	});

    // The event is fired when there's a problem opening the file
    output.on('error', function(err) {
		log.verbose('createZip', 'output stream failure: '+err+' '+JSON.stringify(err));
		var outputStreamErr = errors.getError('OUTPUTSTREAMFAILURE');
		d.reject(outputStreamErr);
    });
    archive.pipe(output);

    // Create the archive from the sourceDir.  Don't include any directory prefix in the archive
    output.on('open', function() {
        archive
          .directory(sourceDir, '')
          .finalize();
    });

	return d.promise;
};
