const fs = require("fs");

function uploadDir(distFolderPath, bucket, prefix) {
  const promises = [];
  
  fs.readdir(distFolderPath, (err, files) => {
    if(!files || files.length === 0) {
      console.log(`provided folder '${distFolderPath}' is empty or does not exist.`);
      console.log('Make sure your project was compiled!');
      return;
    }

    // for each file in the directory
    for (const fileName of files) {

      // get the full path of the file
      const filePath = path.join(distFolderPath, fileName);
      
      // ignore if directory
      if (fs.lstatSync(filePath).isDirectory()) {
        continue;
      }

      // read file contents
      fs.readFile(filePath, (error, fileContent) => {
        // if unable to read file contents, throw exception
        if (error) { throw error; }

        const uploadPromise = new Promise((resolve, reject) => {
          // upload file to S3
          s3.putObject({
            Bucket: bucket,
            Key: fileName,
            Prefix: prefix,
            Body: fileContent
          }, (res) => {
            console.log(`Successfully uploaded '${fileName}'!`);
            resolve();
          });
        });
        promises.push(uploadPromise);
      });
    }
  });
  return Promise.all(promises);
}

module.exports = uploadDir;