var azureHelper = {},
	Azure = require('azure-storage'),
    logger = require('../../../logger'),
	moment = require('moment'),
	mail = require('./../mgmt/mail.js'),
	fs = require('fs'),
	semusiConfig = require('./../../config');

(function (azureHelper) {

    const storeQueue = Azure.createQueueServiceWithSas(semusiConfig.azureApiQueueSASURL, semusiConfig.azureApiStorageSASToken);

	azureHelper.writeAPIDataToSQS=function(queueObject,callback){		
		writeToSQS(queueObject,callback);				
	}
	
	//This function uploads a file to S3 bucket.
	azureHelper.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");
                    }
            	});
        	});
        });
	}

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

	// write data to azure bus queue
	function writeToSQS(data ,callback){	
        // send message to Azure store queue
		storeQueue.createMessage(semusiConfig.azureApiQueueMap[data.key], JSON.stringify(data), {messageTimeToLive:semusiConfig.message_TTL}, function(error, results, response){
            
            if(error){
                callback(false);
                logger.error(`error is => ${error}`);
                mail.sendAlertNotification("Alert: SQS failure.","Could not write data to sqs");
	            fs.writeFile(semusiConfig.SQSFailureLog+"/"+azureHelper.getCurrentEpochTime(), JSON.stringify(data), function(err) {
	                if(err) {
	                    logger.error(`error is => ${err}`);
	                }                
	            });
            }
            else {
                logger.info(`Response from Queue ${JSON.stringify(response)}`)
                callback(true);
            }
        });
	}
}(azureHelper));

module.exports = azureHelper;	