/**
 * Mod module.
 * @module Mod
 * @author iMumu<imumu@foxmail.com>
 * @copyright iMumu
 */

'use strict';

/**
 * Mod
 * @constructor
 */
var Mod = function() {
    this.modules = [];
};

/**
 * Define a module.
 * @example
 * var mod = new Mod();
 * mod.def('LittleBear', {
 *     express: 'express'
 * }, function(mods) {
 *     var app = mods.express();
 * });
 *
 * @param {String} name - module name
 * @param {Object} deps - module dependencies
 * @param {Function} fn - module define function
 */
Mod.prototype.def = function(name, deps, fn) {
    var _deps, _fn;
    if (typeof deps === 'function') {
        _fn = deps;
    }
    else {
        _deps = deps;
        _fn = fn;
    }

    this.modules.push({
        name: name,
        deps: _deps ? _deps : {},
        fn: _fn
    });
};

/**
 * Get all modules
 * @return {Object} modules map
 */
Mod.prototype.getMods = function() {
    var mods = {};
    for (let mod of this.modules) {
        mods[mod.name] = mod.done;
    }
    return mods;
};

/**
 * Run all modules
 */
Mod.prototype.runAll = function() {
    for (let mod of this.modules) {
        if (!mod.done) {
            this.runMod(mod.name);
        }
    }
};

/**
 * Run a module
 * @param {String} name - module name
 */
Mod.prototype.runMod = function(name) {
    var mod = getMod(name, this.modules);
    if (typeof mod.done === 'undefined') {
        var mods = {};
        for (let key in mod.deps) {
            mods[key] = this.runMod(mod.deps[key]);
        }
        try {
            mod.done = mod.fn.call(null, mods);
            if (typeof mod.done === 'undefined') {
                mod.done = null;
            }
        }
        catch (e) {
            console.log(e.stack);
        }
    }
    return mod.done;
};

/**
 * Get module from modules by name
 * @param {String} name - module name
 * @param {Array<Object>} mods
 * @private
 */
function getMod(name, mods) {
    for (let mod of mods) {
        if (name === mod.name) {
            return mod;
        }
    }
}

module.exports = Mod;


@@ -1327,24 +1327,105 @@
 s.modules);%0A
+    if (!mod) %7B%0A        throw new Error(%60Can not load module %22$%7Bname%7D%22.%60);%0A    %7D%0A
     if (type
@@ -1762,24 +1762,81 @@
 catch (e) %7B%0A
+            console.log(%60Run module %22$%7Bname%7D%22 failed:%60);%0A
             

add module error msg