const path = require('path');
const fs = require('fs');
const s3 = require('s3');

function createS3Client(pkg, credsFilePath) {
  let creds;
  const s3Options = Object.assign({}, pkg.config.aws.s3);

  try {
    creds = JSON.parse(
      fs.readFileSync(path.resolve(credsFilePath), 'utf8')
    );
  } catch (e) {
    console.error('Error finding/parsing aws.private.json');
    throw e;
  }

  if (creds.accessKeyId == null || creds.secretAccessKey == null) {
    throw new TypeError(
      'Error could not fine accessKeyId or secretAccessKey in aws.private.json file.'
    );
  }

  Object.assign(s3Options, creds);

  // s3Options is what is used by the AWS SDK
  // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Config.html#constructor-property

  return s3.createClient({
    // default options
    maxAsyncS3: 20,
    s3RetryCount: 3,
    s3RetryDelay: 1000,
    multipartUploadThreshold: 20971520,
    multipartUploadSize: 15728640,
    cacheTTL: 0,
    s3Options
  });
}

module.exports = createS3Client;
