'use strict';

const fs = require('fs');
const log = console.log;

readdirP('./stuff')
  .then(function(files) {
    if (!files.includes('my_file.txt')) {
      throw "Whoops!";
    }

    return readFileP('./stuff/my_file.txt');
  })
  .then(function(data) {
    let new_data =  data + "bleep\n";
    return writeFileP('./stuff/my_file.txt', new_data);
  })
  .then(function() {
    return readFileP('./stuff/my_file.txt');
  })
  .then(function(data) {
    log("my_file now contains...");
    log(data.toString());
  })
  .catch(function(err) {
    log(err);  // Print the error, why not.
    log('Uh oh!');
  });

// Toss the function declarations at the bottom. These functions are
// only necessary because `fs` doesn't use promises natively.

function readdirP(path) {
  return new Promise(function(resolve, reject) {
    fs.readdir(path, function(err, files) {
      if (err) {
        reject(err);
      } else {
        resolve(files);
      }
    });
  });
}

function readFileP(path) {
  return new Promise(function(resolve, reject) {
    fs.readFile(path, function(err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

function writeFileP(path, data) {
  return new Promise(function(resolve, reject) {
    fs.writeFile(path, data, function(err) {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}