'use strict';
let firehose = {};
const AWS = require('aws-sdk'),
logger = require('../../logger'),
      semusiConfig = require('./../config');
  
// setup aws configure    
AWS.config.region = semusiConfig.AWS_REGION;
AWS.config.update({accessKeyId:semusiConfig.AWS_ACCESS_KEY_ID,secretAccessKey:semusiConfig.AWS_SECRET_KEY});
const S3  = new AWS.S3({region : semusiConfig.AWS_REGION}), 
      AWSFirehose = new AWS.Firehose({region : semusiConfig.AWS_REGION});

(function(){
    /*
    * Check s3 bucket if it does exists or does not exists that used in firehose stream
    * @param bucketName is s3 bucket name
    * @param callback is callback function
    */
    firehose.checkIfBucketExists = function(bucketName, callback) {
        S3.listBuckets(function(err, buckets){
          if(err) return callback(err);

          const bucketNames  = buckets.Buckets.map(b => b.Name);
          const bucketOIndex = bucketNames.indexOf(bucketName);
          if( bucketOIndex === -1)
            return callback();

          callback(null, buckets.Buckets[bucketOIndex]);
        });
    }
    /*
    * Create s3 bucket if it does not exists that used in firehose stream
    * @param bucketName is s3 bucket name
    * @param callback is callback function
    */
    firehose.createBucketIfItDoesNotExist = function(bucketName, callback) {
        const s3_config = {
          Bucket: bucketName
        };

        firehose.checkIfBucketExists(bucketName, function(err, bucket){
          if(err) return callback(err);

          if(bucket) return callback(null, bucket);

          S3.createBucket(s3_config, function(err, bucket){
            if(err) return callback(err);

            callback(null, bucket);
          });
        });
    }
    /*
    * Create s3 bucket if it does not exists that used in firehose stream
    * @param bucketName is s3 bucket name
    * @param callback is callback function
    */
    firehose.waitForDStreamToBecomeActive = function(dStreamName, _callback){
        const callback = _callback || createPromiseCallback();
        AWSFirehose.describeDeliveryStream({DeliveryStreamName : dStreamName}, function(err, data) {
            if (err) return callback(err);

            if (data.DeliveryStreamDescription.DeliveryStreamStatus === 'ACTIVE'){
              logger.info(`${dStreamName}:: is now active`);  
              return callback(null, data);
            }

            // The stream is not ACTIVE yet. Wait for another 5 seconds before
            // checking the state again.
            setTimeout(function() {
              waitForDStreamToBecomeActive(dStreamName, callback);
            }, 5000);
        });
        return callback.promise;
    }
    firehose.putRecord = function(dStreamName, data, callback) {
        let recordParams = {
          Record: {
            Data: JSON.stringify(data) + "\n"
          },
          DeliveryStreamName: dStreamName
        };
        AWSFirehose.putRecord(recordParams, callback);
    }
}())
module.exports = firehose;