/* @flow */

var https = require('https');
// var fs    = require('fs');
//
// var vars  = require('./index');
//
// import { formatVersionsAndFilterPrivate } from '';

// module.exports = {
//   // Add modules and their versions to the dependencies object
//   seedDependencies: function(obj: {}) {
//     vars.dependencies = formatVersionsAndFilterPrivate(obj);
//     module.exports.fetchModuleDownloads();
//   },
//
//   // Fetch each module's package.json and add details from it
//   gatherDetails: function(module: string) {
//     var modulePath = vars.rootDir + 'node_modules/' + module + '/package.json';
//     var dependency = vars.dependencies[module];
//     fs.readFile(modulePath, function(err, data) {
//       if (err) console.error(err);
//       var details = JSON.parse(data.toString('utf8'));
//       dependency.name = details.name;
//       dependency.url = details.homepage || details.repository ?
//         details.repository.url.replace(/\w*\+/, '') : '' ;
//       dependency.description = details.description;
//     });
//   },

  // Batch retrieve the npm download counts for all modules for the past month

// httpsGetPromise.then((result) => {
//   var resultObj = JSON.parse(result.toString('utf8'));
//   Object.keys(resultObj).forEach(function(key) {
//     if (vars.dependencies[key]) {
//       vars.dependencies[key].downloads = resultObj[key] ?
//       resultObj[key].downloads : null;
//       outCount++;
//     }
//   });
// })

export function NpmConfig(dependencies: {}) {
  return {
    hostname: 'api.npmjs.org',
    path: '/downloads/point/last-month/' + Object.keys(dependencies).join(','),
    method: 'GET',
    headers: {
      'User-Agent': 'cachilders/backpat'
    }
  };
}

export function httpsGetPromise(opts: {}) {
  return new Promise((resolve, reject) => {
    https.get(opts, (res) => {
      const body = [];
      res.on('data', (chunk) => body.push(chunk));
      res.on('end', () => resolve(Buffer.concat(body).toString()));
      res.on('error', reject);
    });
  });
}

@@ -10,37 +10,100 @@
 */%0A%0A
-var
+import
  https 
-= require('https');
+from 'https';%0Aimport %7B readFile %7D from 'fs';%0Aimport %7B has %7D from 'lodash/has';%0A
 %0A// 
@@ -1529,16 +1529,511 @@
 );%0A// %7D)
+%0A//%0A%0Aexport const rootDir = process.cwd() + '/';%0A%0Aexport const readPackageJson = (f: Function) =%3E %7B%0A  if (typeof f !== 'function') %7B%0A    throw new TypeError(%60Expected a function but received $%7B typeof f %7D instead%60);%0A  %7D%0A  return new Promise((resolve, reject) =%3E %7B%0A    readFile(rootDir + '/package.json', (err, data) =%3E %7B%0A      if (err) %7B%0A        reject(err);%0A      %7D%0A      resolve(JSON.parse(data.toString()));%0A    %7D);%0A  %7D)%0A  .then(f)%0A  .catch((reason) =%3E %7B%0A    throw new Error(reason);%0A  %7D);%0A%7D;
 %0A%0Aexport

refactor to ES6 Harmony and write functionality for readPackageJson