var awsHelper = {},
	AWS = require('aws-sdk'),
	logger = require('../../../logger'),
	moment = require('moment'),
	mail = require('./../mgmt/mail.js'),
	fs = require('fs'),
	semusiConfig = require('./../../config');

(function (awsHelper) {

	awsHelper.writeAPIDataToSQS=function(queueObject,callback){
		var queue = semusiConfig.apiQueueMap[queueObject.key];
		writeToSQS(queueObject,queue,callback);
	}

	//This function uploads a file to S3 bucket.
	awsHelper.uploadFileToS3 = function(bucket,key,filePath,filename){
		AWS.config.region = semusiConfig.AWS_REGION;
		AWS.config.update({accessKeyId:semusiConfig.AWS_ACCESS_KEY_ID,secretAccessKey:semusiConfig.AWS_SECRET_KEY});

		var s3bucket = new AWS.S3({params: {Bucket: bucket, Key: key}});

         s3bucket.createBucket({Bucket:bucket},function(err,data){
			logger.error(`error is => ${err}`);
                
            //create the bucket or the folder
            fs.readFile(filePath, function (err, data) {
                if (err) { throw err; }
                var params = {Bucket:bucket,Key: key+'/'+filename, Body: data};
                s3bucket.upload(params, function(err, data) {
                    if (err) {
						logger.error(`error uploading data ${err}`);
                    } else {
						logger.info("Successfully uploaded data to myBucket/myKey");      
                    }
            	});
        	});
        });
	}

	//This function writes backupdata to kinesis.
	awsHelper.sendDataToKinesis = function(backupData){
		try{

			var datajson = JSON.parse(backupData.data);
			var appid = backupData.app_id;
			var did = datajson.mobileid;

			if(datajson.internetaccess && datajson.internetaccess.length>0){
				var internetaccessData = {
					appid : appid,
					did : did,
					data : datajson.internetaccess
				}
				writeToKinesis("internetaccessdata", internetaccessData);
			}
			if(datajson.applicationaccess && datajson.applicationaccess.length>0){
				var applicationaccessData = {
					appid : appid,
					did : did,
					data : datajson.applicationaccess
				}
				writeToKinesis("applicationaccessdata", applicationaccessData);
			}

			if(datajson.batterydata && datajson.batterydata.length>0){
				var batteryData = {
					appid : appid,
					did : did,
					data : datajson.batterydata
				}
				writeToKinesis("batterydata", batteryData);
			}
			if(datajson.sms && datajson.sms.length>0){
				var smsData = {
					appid : appid,
					did : did,
					data : datajson.sms
				}
				writeToKinesis("smsdata", smsData);
			}
			if(datajson.emails && datajson.emails.length>0){
				var emailsData = {
					appid : appid,
					did : did,
					data : datajson.emails
				}
				writeToKinesis("emaildata", emailsData);
			}
			if(datajson.appusagedata && datajson.appusagedata.length>0){
				var appusageData = {
					appid : appid,
					did : did,
					data : datajson.appusagedata
				}
				writeToKinesis("appusagedata", appusageData);
			}
			if(datajson.places && datajson.places.length>0){
				var placesData = {
					appid : appid,
					did : did,
					data : datajson.places
				}
				writeToKinesis("placesdata", placesData);
			}
		}
		catch(e){
			logger.error(`Error while parsing backup data => ${e}`);
			    
			    
		}
	}

	// get current utc epoph time
  awsHelper.getCurrentEpochTime = function(){
      var d = new Date();
      d = moment.utc(d);
      return parseInt(d.valueOf()/1000);
  }

	function writeToKinesis(streamName,data) {
		AWS.config.region = semusiConfig.AWS_REGION;
		AWS.config.update({accessKeyId:semusiConfig.AWS_ACCESS_KEY_ID,secretAccessKey:semusiConfig.AWS_SECRET_KEY});

		var kinesis = new AWS.Kinesis({region : semusiConfig.AWS_REGION});
	  	var partitionKey = 'pk-' + awsHelper.getCurrentEpochTime();
	  	var recordParams = {
	    	Data: JSON.stringify(data),
	    	PartitionKey: partitionKey,
	    	StreamName: streamName
	  	};

	  	kinesis.putRecord(recordParams, function(err, data) {
	    	if (err) {
				logger.error(`error is => ${err}`);
	    	}
	  	});
	};

	function createStream(streamName, numberOfShards, callback) {
	  var params = {
	    ShardCount: numberOfShards,
	    StreamName: streamName
	  };

	  // Create the new stream if it does not already exist.
	  kinesis.createStream(params, function(err, data) {
	    if (err && err.code !== 'ResourceInUseException') {
	      	callback(err);
	      	return;
	    }
	    // Make sure the stream is in the ACTIVE state before
	    // you start pushing data.
	    waitForStreamToBecomeActive(streamName, callback);
	  });
	}

	function waitForStreamToBecomeActive(streamName, callback) {
	  kinesis.describeStream({StreamName : streamName},
	    function(err, data) {
	      	if (err) {
	    		callback(err);
	        	return;
	      	}

	      	if (data.StreamDescription.StreamStatus === 'ACTIVE') {
	        	callback();
	      	}
	      	// The stream is not ACTIVE yet. Wait for another 5 seconds before
	      	// checking the state again.
	      	else {
	        	setTimeout(function() {
	          		waitForStreamToBecomeActive(streamName, callback);
	        	}, 5000);
	      	}
	    }
	  );
	}

	function writeToSQS(data,queue,callback){
		AWS.config.region = semusiConfig.AWS_REGION;
        AWS.config.update({accessKeyId:semusiConfig.AWS_ACCESS_KEY_ID,secretAccessKey:semusiConfig.AWS_SECRET_KEY});
		var sqs = new AWS.SQS();
	    var boxParams = {
	        MessageBody: JSON.stringify(data),
	        QueueUrl: queue,
	        DelaySeconds: 0
	    };
	    sqs.sendMessage(boxParams, function (err, data) {
	        if (err) {
	        	callback(false);
				logger.error(`error is => ${err}`);
	            mail.sendAlertNotification("Alert: SQS failure.","Could not write data to sqs");
	            fs.writeFile(semusiConfig.SQSFailureLog+"/"+awsHelper.getCurrentEpochTime(), data, function(err) {
	                if(err) {
						logger.error(`error is => ${err}`);
	                }
	            });
	        }
	        else{
	        	callback(true);
	        }
	    });
	}




}(awsHelper));

module.exports = awsHelper;
