'use strict';

var fs = require('fs');
var path = require('path');

var Promise = require('promise-polyfill');
var promisify = require('es6-promisify');

module.exports = function (name) {
    check(name);

    var dir = 'node_modules/' + name;

    var inner = resolveModule(__dirname, '../', dir);
    var outer = resolveModule(__dirname, '../../', name);

    return Promise.resolve().then(inner).catch(outer);
};

function check(name) {
    if (typeof name !== 'string') throw Error('name should be string!');
}

function resolveModule() {
    /* stat: not global becouse of tests */
    var stat = promisify(fs.stat);
    var dir = path.resolve.apply(path, arguments);
    var getDir = function getDir() {
        return dir;
    };

    return function () {
        return stat(dir).then(getDir);
    };
}