'use strict';
// Fake Keys to detect
// MAILGUN_API_KEY: 84d82821248fa8gg8gh8a 1-4-2019


var async = require('async');
var _ = require('lodash');
var glob = require('glob');
var path = require('path');
var findParentDir = require('find-parent-dir');

function buildContext(config, cb) {
  async.waterfall([
    function(cb) {
      findParentDir(config.cwd, 'package.json', cb);
    },
    function(nodePackageDir, cb) {
      config.base = nodePackageDir;
      async.parallel({
        filesByGlob: function(cb) {
          async.map(config.globs, function(globStr, cb) {
            glob(globStr, {cwd: nodePackageDir}, cb);
          }, cb);
        },
        nodePackageDir: function(cb) {
          cb(null, nodePackageDir);
        }
      }, cb);
    },
    function(res, cb) {
      var packageJSON = require(path.join(res.nodePackageDir, 'package.json'));
      var builtinModules = [
        'assert',
        'fs',
        'http',
        'https',
        'streams',
        'url',
        'util'
      ];
      config.nodeDependencies = builtinModules.concat(
          _.keys(_.merge({}, packageJSON.dependencies, packageJSON.devDependencies))
      );

      var files = _(res.filesByGlob)
        .flatten()
        .reject(function(file) {
          return _.contains(file, 'node_modules');
        }).value();
      config.projectFilenames = files;
      cb();
    }
  ], cb);
}

// trailing whitespace W102
// config:
//   globs - globs to pattern match when finding project files.
//   aliases - alias names for packages (e.g. _ for lodash).
//
function run(config, cb) {
  config.globs = [
    '+(lib|test|scripts)/**/*.js'
  ];

  config.aliases = {
    _: 'lodash',
    expect: 'expectJs', // _.camelCase even removes periods.
    Joi: 'joi'
  };

  async.series([
    function(cb) {
      buildContext(config, cb);
    },
    function(cb) {
      require('./lib/fixRequires').insertMissingRequires(config, cb);
    }
  ], function(err) {
    cb(err, config.content.join('\n'));
  });
}

module.exports = {
  run: run
};
