// jscs:disable maximumLineLength
'use strict';

var assert = require('assert');
var Promise = require('../');

/*
  Copyright 2009–2012 Kristopher Michael Kowal. All rights reserved.
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  IN THE SOFTWARE.
*/

describe('Promise#nodify', function() {
  var mkspy = function(calls) {
    return function spy() {
      var args = Array.prototype.slice.call(arguments);
      args.unshift(this);
      calls.push(args);
    };
  };

  it('calls back with a resolution', function() {
    var calls = [];
    var spy = mkspy(calls);

    Promise.resolve(10).nodify(spy);

    return Promise.delay(null, 10).then(function() {
      assert.deepEqual(calls, [[undefined, null, 10]]);
    });
  });

  it('calls back with an error', function() {
    var calls = [];
    var spy = mkspy(calls);

    Promise.reject(10).nodify(spy);

    return Promise.delay(null, 10).then(function() {
      assert.deepEqual(calls, [[undefined, 10]]);
    });
  });

  it('forwards a promise', function() {
    return Promise.resolve(10).nodify().then(function(ten) {
      assert.deepEqual(ten, 10);
    });
  });

});


// Should be the last test because it is ridiculously hard to test
// if something throws in the node process

var isNodeJS = typeof process !== 'undefined' &&
  typeof process.execPath === 'string';

if (isNodeJS) {
  describe('nodify', function() {

    var h = [];

    function clearHandlers() {
      var originalException;
      while (true) {
        originalException = process.listeners('uncaughtException').pop();
        if (!originalException) { break; }
        process.removeListener('uncaughtException', originalException);
        h.push(originalException);
      }
    }

    function clearHandlersNoRestore() {
      var originalException;
      while (true) {
        originalException = process.listeners('uncaughtException').pop();
        if (!originalException) { break; }
        process.removeListener('uncaughtException', originalException);
      }
    }

    function addHandlersBack() {
      for (var i = 0, len = h.length; i < len; ++i) {
        process.addListener('uncaughtException', h[i]);
      }
    }
    var e = new Error();
    function thrower() {
      throw e;
    }

    it('throws normally in the node process if the function throws', function(done) {
      clearHandlers();
      var promise = Promise.resolve(10);
      var turns = 0;
      process.nextTick(function() {
        turns++;
      });
      promise.nodify(thrower);
      process.addListener('uncaughtException', function(err) {
        clearHandlersNoRestore();
        assert(err === e);
        assert(turns === 1);
        done();
      });
    });
  });
}
