var path = require('path');
var resolve = require('resolve');
var Immutable = require('immutable');

var Promise = require('../utils/promise');
var error = require('../utils/error');
var timing = require('../utils/timing');

var validatePlugin = require('./validatePlugin');

// Return true if an error is a "module not found"
// Wait on https://github.com/substack/node-resolve/pull/81 to be merged
function isModuleNotFound(err) {
    return err.code == 'MODULE_NOT_FOUND' || err.message.indexOf('Cannot find module') >= 0;
}

/**
    Load a plugin in a book

    @param {Book} book
    @param {Plugin} plugin
    @param {String} pkgPath (optional)
    @return {Promise<Plugin>}
*/
function loadPlugin(book, plugin) {
    var logger = book.getLogger();

    var name = plugin.getName();
    var pkgPath = plugin.getPath();

    // Try loading plugins from different location
    var p = Promise()
    .then(function() {
        var packageContent;
        var content;

        // Locate plugin and load package.json
        try {
            var res = resolve.sync('./package.json', { basedir: pkgPath });

            pkgPath = path.dirname(res);
            packageContent = require(res);
        } catch (err) {
            if (!isModuleNotFound(err)) throw err;

            packageContent = undefined;
            content = undefined;

            return;
        }

        // Load plugin JS content
        try {
            content = require(pkgPath);
        } catch(err) {
            // It's no big deal if the plugin doesn't have an "index.js"
            // (For example: themes)
            if (isModuleNotFound(err)) {
                content = {};
            } else {
                throw new error.PluginError(err, {
                    plugin: name
                });
            }
        }

        // Update plugin
        return plugin.merge({
            'package': Immutable.fromJS(packageContent),
            'content': Immutable.fromJS(content)
        });
    })

    .then(validatePlugin);

    p = timing.measure('plugin.load', p);

    logger.info('loading plugin "' + name + '"... ');
    return logger.info.promise(p);
}


module.exports = loadPlugin;

@@ -943,16 +943,41 @@
 ontent;%0A
+        var packageMain;%0A
         
@@ -1410,28 +1410,29 @@
 / Lo
-ad plugin JS content
+cate the main package
 %0A   
@@ -1458,33 +1458,148 @@
     
-content = require(
+var indexJs = path.normalize(packageContent.main %7C%7C 'index.js');%0A            packageMain = resolve.sync('./' + indexJs, %7B basedir: 
 pkgPath
+ %7D
 );%0A 
@@ -1612,16 +1612,17 @@
  %7D catch
+ 
 (err) %7B%0A
@@ -1637,144 +1637,171 @@
     
-// It's no big deal if the plugin doesn't have an %22index.js%22
+if (!isModuleNotFound(err)) throw err;%0A            packageMain = undefined;
 %0A      
+  %7D%0A%0A
       
+  
 // 
-(For example: themes)%0A            if (isModuleNotFound(err))
+Load plugin JS content%0A        if (packageMain) %7B%0A            try
  %7B%0A 
@@ -1829,10 +1829,28 @@
 t = 
-%7B%7D
+require(packageMain)
 ;%0A  
@@ -1865,12 +1865,18 @@
   %7D 
-else
+catch(err)
  %7B%0A 

Improve plugin loading to not fake module errors