var util = require('util');
var npm = require('npm');
var _ = require('lodash');
var async = require('async');
var path = require('path');

require('es6-collections');

var cacheLocation = '/Users/jryans/projects/core-score/npmcache'; 

var npmConfig = {
  cache: cacheLocation
};

var coreModules = require('repl')._builtinLibs;

exports.scoreModules = scoreModules;

function scoreModules(cb) {
  npm.load(npmConfig, function(err) {
    /*npm.commands.search('mkdirp', true, function(err, data) {
      if (err) {
        return cb(err);
      }

      // Object.keys(data).slice(0, 1).forEach(grabPackage);
    });*/

    new ScoringModule('mkdirp').score(cb);
  });
}

function ScoringModule(moduleName) {
  var self = this;

  self.moduleName = moduleName;
  self.filesSeen = new Set();
  self.coreCount = new Map();
  
  coreModules.forEach(function(coreMod) {
    self.coreCount.set(coreMod, 0);
  });
}

ScoringModule.prototype.score = function(cb) {
  var self = this;
  async.waterfall([
    self.grabPackage.bind(self),
    self.findMain.bind(self)
  ], cb);
};

ScoringModule.prototype.seen = function(modRelPath) {
  return this.filesSeen.has(modRelPath);
};

ScoringModule.prototype.grabPackage = function(cb) {
  var self = this;
  npm.commands.info([self.moduleName, 'dist.tarball'], true, function(err, info) {
    if (err) {
      return cb(err);
    }

    var tarUrl = _.values(info)[0]['dist.tarball'];

    npm.commands.cache.add(tarUrl, function(err, json) {
      if (err) {
        return cb(err);
      }

      var modulePath = path.resolve(cacheLocation, self.moduleName, _.keys(info)[0], 'package');

      cb(null, json, modulePath);
    });
  });
};

ScoringModule.prototype.findMain = function(json, modulePath, cb) {
  var self = this;

  var mainFile;

  cb(new Error("No main file found for " + self.moduleName));
};

@@ -131,16 +131,40 @@
 'path');
+%0Avar fs = require('fs');
 %0A%0Arequir
@@ -1801,16 +1801,414 @@
 mainFile
+Path = _.find(%5B%0A    (json && json.main) ? json.main : null,%0A    (json && json.main) ? json.main + '.js' : null,%0A    './index.js'%0A  %5D, function(testPath) %7B%0A    if (!testPath) %7B%0A      return false;%0A    %7D%0A %0A    testPath = path.resolve(modulePath, testPath);%0A    if (fs.existsSync(testPath)) %7B%0A      return path.relative(modulePath, testPath);%0A    %7D%0A%0A    return false;%0A  %7D);%0A%0A  util.debug(mainFilePath)
 ;%0A%0A  cb(

Add main file search