/*
	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.
*/


//private modules
var messages = require('./externalizedStrings');
var strings = require('ibm-strings');
//public modules
var fs = require('fs');
var log = require('npmlog');
var path = require('path');
var os = require('os');
var q = require('q');
var rimraf = require('rimraf');

function createDirectory(d, dirpath) {
	fs.mkdir(dirpath, function (err) {
		if(!err) {
			//Handle abrupt exits
			process.on('SIGINT', function () {
				try {
					rimraf.sync(dirpath);
				} catch (err) {
					log.silly(strings.format(messages.temporaryDirectoryCannotBeDeleted, err));
				}
			});

			d.resolve(dirpath);
		} else {
			log.verbose('temporaryDirectory', 'Temporary directory could not be created: '+err+' '+JSON.stringify(err));
			var errStr = strings.format(messages.temporaryDirectoryCannotBeCreated, err);
			d.reject(errStr);
		}
	});
}

function cleanUpTempDir(dirpath) {
	var d = q.defer();
	if(!dirpath) {
		log.silly('temporaryDirectory', 'cleanUpTempDir dirpath argument is undefined');
		d.resolve();
	} else {
		rimraf(dirpath, function (err) {
			if(err) {
				log.verbose('temporaryDirectory', 'Temporary directory could not be deleted: '+err+' '+JSON.stringify(err));
				var errStr = strings.format(messages.temporaryDirectoryCannotBeDeleted, err);
				d.reject(errStr);
			}
			else {
				d.resolve();
			}
		});
	}

	return d.promise;
}

function createTempDir(pathName) {
	var d = q.defer();
	var dirpath = path.join(os.tmpdir(), pathName);

	fs.exists(dirpath, function (exists) {
		if(!exists) {
			createDirectory(d, dirpath);
		} else {
			cleanUpTempDir(dirpath)
			.then(function () {
				createDirectory(d, dirpath);
			}, function (err) {
				log.verbose('temporaryDirectory', 'Temporary directory already exists: '+err+' '+JSON.stringify(err));
				var errStr = strings.format(messages.temporaryDirectoryCannotBeDeleted, err);
				d.reject(errStr);
			});
		}
	});

	return d.promise;
}

module.exports = {
		create: createTempDir,
		cleanUp: cleanUpTempDir
};
