const inquirer = require('inquirer');
const chalk = require('chalk');

function checkForExistingRelease(s3Client, bucket, prefix) {
  return new Promise(function (resolve, reject) {
    s3Client.listObjects({
        Bucket: bucket,
        MaxKeys: 2,
        Prefix: prefix
      }, function(err, data) {
        if (err) {
          console.error('Cannot verify whether this version already exists on S3.');
          console.error(err);
          return promptForContinue(resolve, reject, 'Release anyway (files might be overwritten)?');
        } else {
          if (!data.Contents || data.Contents.length === 0) {
            resolve();
            return;
          }
          return promptForContinue(resolve, reject, `This version already exists in the ${chalk.default.yellow(bucket)} bucket. Overwrite?`);
        }
      }
    );
  });
}

function promptForContinue(resolve, reject, message) {
  return inquirer.prompt({
    message: message,
    name: 'confirm',
    type: 'confirm',
    default: false
  }).then(function (value) {
    if (value.confirm) {
      console.log(chalk.default.magentaBright('Files without changes will not be uploaded.'));
      resolve();
    }
    else { reject(); }
  });
}

module.exports = checkForExistingRelease;
