'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.buildCredentials = exports.buildKinesisClient = exports.buildKinesisConfiguration = undefined;

var _global = require('aws-sdk/global');

var _kinesis = require('aws-sdk/clients/kinesis');

var _kinesis2 = _interopRequireDefault(_kinesis);

var _config = require('./config');

var _Fetcher = require('../util/Fetcher');

var _Fetcher2 = _interopRequireDefault(_Fetcher);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var buildKinesisConfiguration = exports.buildKinesisConfiguration = function buildKinesisConfiguration(_ref) {
  var configuration = _ref.configuration,
      credentials = _ref.credentials;

  var serverTime = configuration.server_time;
  if (serverTime) _global.config.systemClockOffset = Date.parse(serverTime) - Date.now();
  return {
    client: buildKinesisClient(configuration, credentials),
    streamConfigs: (0, _config.assembleStreamConfigs)(configuration)
  };
};

var buildKinesisClient = exports.buildKinesisClient = function buildKinesisClient(configuration, credentials) {
  var kinesisConfig = Object.assign({}, (0, _config.assembleKinesisConfig)(configuration.client_configuration), { credentials: credentials });

  return new _kinesis2.default(kinesisConfig);
};

var buildCredentials = exports.buildCredentials = function buildCredentials(credentialParams) {
  var creds = new _global.Credentials(credentialParams.access_key_id, credentialParams.secret_access_key, credentialParams.session_token // credentialParams
  );
  creds.expireTime = Date.parse(credentialParams.expiration);
  return creds;
};

var getKinesisConfig = function getKinesisConfig(quizSessionId) {
  var fetcher = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new _Fetcher2.default();

  return new Promise(function (resolve, reject) {
    var url = '/api/quiz_sessions/' + quizSessionId + '/kinesis_credentials';
    fetcher.post(url).then(function (configuration) {
      var config = buildKinesisConfiguration({
        configuration: configuration,
        credentials: buildCredentials(configuration.credentials)
      });

      resolve(config);
    }).then(function (err) {
      return reject(err);
    });
  });
};

exports.default = getKinesisConfig;