'use strict';

var fs = require('fs');
var path = require('path');
var test = require('tape');
var resolvePath = require('./resolve-path');

var stat = fs.stat;


test('resolve-path: args', function (t) {
    t.throws(resolvePath, /name should be string!/, 'should throw when name not string');
    t.end();
});

test('resolve-path: module installed in inner directory', function (t) {
    var expect = path.resolve(__dirname, '..', 'node_modules/monaco');

    mock();
    resolvePath('monaco').then(function (name) {
        t.equal(name, expect, 'should return path in inner directory');
        t.end();
        unmock();
    });
});

test('resolve-path: module installed in outer directory', function (t) {
    var expect = path.resolve(__dirname, '../../', 'monaco');

    mockFirstError();
    resolvePath('monaco').then(function (name) {
        t.equal(name, expect, 'should return path in outer directory');
        t.end();
        unmock();
    });
});

test('resolve-path: module not installed', function (t) {
    mock(Error());
    resolvePath('monaco').catch(function () {
        t.pass('should reject when module not found');
        unmock();
        t.end();
    });
});

function mockFirstError() {
    var onceError = void 0;

    fs.stat = function (name, fn) {
        if (onceError) {
            fn();
        } else {
            onceError = true;
            fn(Error('some error'));
        }
    };
}

function mock() {
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
    }

    fs.stat = function (name, fn) {
        fn.apply(undefined, args);
    };
}

function unmock() {
    fs.stat = stat;
}