const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const rootPath = __dirname.split('node_modules')[0];
const AWS = require('aws-sdk');

function getAwsPrivateFile() {
  const fileName = 'aws.private.json';
  let prefix = '';
  let file = null;
  let maxDepth = 2;
  do {
    file = path.resolve(rootPath, prefix + fileName);
    prefix += '../';
  } while (!fs.existsSync(file) && maxDepth--);

  return file;
}

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

  try {
    creds = JSON.parse(fs.readFileSync(credsFile, 'utf8'));
  } catch (e) {
    console.error(`Error finding/parsing ${chalk.default.cyan(credsFile)}`);
    return;
  }

  if (creds.accessKeyId == null || creds.secretAccessKey == null) {
    console.error(`Error could not fine accessKeyId or secretAccessKey in ${chalk.default.cyan(credsFile)} file.`);
    return;
  }

  AWS.config.update({
    accessKeyId: creds.accessKeyId,
    secretAccessKey: creds.secretAccessKey,
    maxRetries: 3,
  });

  return new AWS.S3(s3Options);

  // 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;
