'use strict';

var defineProperties = require('define-properties');
var test = require('tape');
var callBind = require('call-bind');
var functionsHaveNames = require('functions-have-names')();
var hasStrictMode = require('has-strict-mode')();
var forEach = require('for-each');
var debug = require('object-inspect');
var v = require('es-value-fixtures');
var hasSymbols = require('has-symbols/shams')();
var hasPropertyDescriptors = require('has-property-descriptors')();
var iterate = require('iterate-iterator');

var index = require('../Iterator.prototype.drop');
var impl = require('../Iterator.prototype.drop/implementation');

var fnName = 'drop';

var isEnumerable = Object.prototype.propertyIsEnumerable;

var testIterator = require('./helpers/testIterator');

module.exports = {
	tests: function (drop, name, t) {
		t['throws'](
			function () { return new drop(); }, // eslint-disable-line new-cap
			TypeError,
			'`' + name + '` itself is not a constructor'
		);

		forEach(v.primitives.concat(v.objects), function (nonIterator) {
			t['throws'](
				function () { iterate(drop(nonIterator, 0)); },
				TypeError,
				debug(nonIterator) + ' is not an Object with a callable `next` method'
			);

			var badNext = { next: nonIterator };
			t['throws'](
				function () { iterate(drop(badNext, 0)); },
				TypeError,
				debug(badNext) + ' is not an Object with a callable `next` method'
			);
		});

		t.test('observable lookups', { skip: !hasPropertyDescriptors }, function (st) {
			var effects = [];

			var obj = {};
			Object.defineProperty(obj, 'next', {
				configurable: true,
				enumerable: true,
				get: function next() {
					effects.push('get next');
					return function () {
						return { done: true, value: undefined };
					};
				}
			});
			drop(obj, {
				valueOf: function valueOf() {
					effects.push('ToNumber limit');
					return 0;
				}
			});

			st.deepEqual(effects, [
				'ToNumber limit',
				'get next'
			]);
			st.end();
		});

		t.test('early-error calls return on receiver', function (st) {
			var returnCalls = 0;
			var obj = {
				next: function () { return { done: true }; },
				'return': function () {
					returnCalls += 1;
					return { done: true };
				}
			};

			st['throws'](
				function () { drop(obj, NaN); },
				RangeError,
				'NaN throws RangeError'
			);
			st.equal(returnCalls, 1, 'return called on receiver for NaN');

			returnCalls = 0;
			st['throws'](
				function () { drop(obj, -1); },
				RangeError,
				'-1 throws RangeError'
			);
			st.equal(returnCalls, 1, 'return called on receiver for negative limit');

			returnCalls = 0;
			st['throws'](
				function () { drop(obj, { valueOf: function () { throw new SyntaxError('bad'); } }); },
				SyntaxError,
				'ToNumber throwing calls return'
			);
			st.equal(returnCalls, 1, 'return called on receiver when ToNumber throws');

			st.end();
		});

		t.test('IteratorStepValue throwing does not close iterator', { skip: !hasSymbols }, function (st) {
			var returnCalls = 0;
			var throwOnNext = false;
			var iter = {
				next: function () {
					if (throwOnNext) {
						throw new EvalError('next threw');
					}
					return { done: false, value: 1 };
				},
				'return': function () {
					returnCalls += 1;
					return { done: true };
				}
			};
			iter[Symbol.iterator] = function () { return iter; };

			var dropped = drop(iter, 0);
			dropped.next(); // consume one value
			throwOnNext = true;

			st['throws'](
				function () { dropped.next(); },
				EvalError,
				'next() throwing propagates'
			);
			st.equal(returnCalls, 0, 'return NOT called on protocol violation');

			st.end();
		});

		var arr = [1, 2, 3];

		t.test('actual iteration', { skip: !hasSymbols }, function (st) {
			var iterator = callBind(arr[Symbol.iterator], arr);

			st['throws'](
				function () { drop(iterator(), -3); },
				RangeError,
				'-3 is not >= 0'
			);

			st['throws'](
				function () { return new drop(iterator()); }, // eslint-disable-line new-cap
				TypeError,
				'`' + name + '` iterator is not a constructor'
			);
			st['throws'](
				function () { return new drop(iterator(), 0); }, // eslint-disable-line new-cap
				TypeError,
				'`' + name + '` iterator is not a constructor'
			);

			testIterator(iterator(), [1, 2, 3], st, 'original');
			testIterator(drop(iterator(), 0), [1, 2, 3], st, 'drop 0');
			testIterator(drop(iterator(), 1), [2, 3], st, 'drop 1');
			testIterator(drop(iterator(), 2), [3], st, 'drop 2');
			testIterator(drop(iterator(), 3), [], st, 'drop 3');
			testIterator(drop(iterator(), Infinity), [], st, 'drop ∞');

			st.test('262: limit-tonumber', function (s2t) {
				// ToNumber coercion
				testIterator(drop(iterator(), '1'), [2, 3], s2t, 'string "1" coerced to 1');
				testIterator(drop(iterator(), 1.9), [2, 3], s2t, '1.9 truncated to 1');
				testIterator(drop(iterator(), { valueOf: function () { return 1; } }), [2, 3], s2t, 'object with valueOf');
				testIterator(drop(iterator(), true), [2, 3], s2t, 'true coerced to 1');
				testIterator(drop(iterator(), null), [1, 2, 3], s2t, 'null coerced to 0');

				s2t.end();
			});

			st.test('262: limit-tonumber-throws', function (s2t) {
				s2t['throws'](
					function () { drop(iterator(), { valueOf: function () { throw new EvalError('valueOf threw'); } }); },
					EvalError,
					'throws when valueOf throws'
				);

				s2t['throws'](
					function () { drop(iterator(), Symbol('test')); },
					TypeError,
					'throws when limit is a Symbol'
				);

				s2t.end();
			});

			st.test('262: limit-rangeerror', function (s2t) {
				s2t['throws'](function () { drop(iterator(), -1); }, RangeError, '-1 throws RangeError');
				s2t['throws'](function () { drop(iterator(), -Infinity); }, RangeError, '-Infinity throws RangeError');
				s2t['throws'](function () { drop(iterator(), NaN); }, RangeError, 'NaN throws RangeError');

				s2t.end();
			});

			st.test('262: result is iterator', function (s2t) {
				var iter = drop(iterator(), 1);
				s2t.equal(typeof iter.next, 'function', 'has next method');
				s2t.equal(typeof iter[Symbol.iterator], 'function', 'has Symbol.iterator method');
				s2t.equal(iter[Symbol.iterator](), iter, 'Symbol.iterator returns itself');

				s2t.end();
			});

			st.test('262: get next method only once', { skip: !hasPropertyDescriptors }, function (s2t) {
				var nextGets = 0;
				var testIter = {};
				Object.defineProperty(testIter, 'next', {
					get: function () {
						nextGets += 1;
						return function () {
							return { done: true, value: undefined };
						};
					}
				});

				var iter = drop(testIter, 1);
				s2t.equal(nextGets, 1, 'next retrieved once on creation');
				iter.next();
				s2t.equal(nextGets, 1, 'next not retrieved again');

				s2t.end();
			});

			st.test('262: next method returns non-object throws', function (s2t) {
				var badIterator = {
					next: function () {
						return null;
					}
				};

				var iter = drop(badIterator, 1);
				s2t['throws'](function () { iter.next(); }, TypeError, 'throws when next returns null');

				s2t.end();
			});

			st.test('262: next method returns throwing done', { skip: !hasPropertyDescriptors }, function (s2t) {
				var throwingIterator = {
					next: function () {
						var result = { value: 1 };
						Object.defineProperty(result, 'done', {
							get: function () {
								throw new EvalError('done getter threw');
							}
						});
						return result;
					}
				};

				var iter = drop(throwingIterator, 1);
				s2t['throws'](function () { iter.next(); }, EvalError, 'throws when done getter throws');

				s2t.end();
			});

			st.test('262: next method throws', function (s2t) {
				var throwingIterator = {
					next: function () {
						throw new EvalError('next threw');
					}
				};

				var iter = drop(throwingIterator, 1);
				s2t['throws'](function () { iter.next(); }, EvalError, 'throws error from next');

				s2t.end();
			});

			st.test('262: throws TypeError when generator is running', function (s2t) {
				var reentrantIterator;
				var testIter = {
					next: function () {
						reentrantIterator.next();
						return { done: false, value: 1 };
					}
				};

				reentrantIterator = drop(testIter, 0);
				s2t['throws'](function () { reentrantIterator.next(); }, TypeError, 'throws on reentrant next()');

				s2t.end();
			});

			st.test('262: limit-equals-total', function (s2t) {
				testIterator(drop(iterator(), 3), [], s2t, 'drop exactly 3 from 3-item iterator');

				s2t.end();
			});

			st.test('262: limit-greater-than-total', function (s2t) {
				testIterator(drop(iterator(), 5), [], s2t, 'drop 5 from 3-item iterator');
				testIterator(drop(iterator(), 100), [], s2t, 'drop 100 from 3-item iterator');

				s2t.end();
			});

			st.test('262: limit-less-than-total', function (s2t) {
				testIterator(drop(iterator(), 1), [2, 3], s2t, 'drop 1 from 3-item iterator');
				testIterator(drop(iterator(), 2), [3], s2t, 'drop 2 from 3-item iterator');

				s2t.end();
			});

			st.test('262: exhaustion does not call return', function (s2t) {
				var returnCalls = 0;

				var testIter = {
					next: function () {
						return { done: true, value: undefined };
					},
					'return': function () {
						returnCalls += 1;
						return { done: true, value: undefined };
					}
				};

				var iter = drop(testIter, 1);
				iter.next();
				s2t.equal(returnCalls, 0, 'return not called on exhaustion');

				s2t.end();
			});

			st.end();
		});

		t.test('262: test/built-ins/Iterator/prototype/drop/get-return-method-throws', { skip: !hasPropertyDescriptors }, function (st) {
			var badIterator = {
				next: function next() {
					return {
						done: false,
						value: 1
					};
				}
			};

			Object.defineProperty(badIterator, 'return', {
				configurable: true,
				enumerable: true,
				get: function () { throw new SyntaxError(); }
			});

			var iter = drop(badIterator, 1);
			iter.next();

			st['throws'](
				function () { iter['return'](); },
				SyntaxError,
				'gets the `return` method, whose getter throws'
			);

			st.end();
		});

		t.test('262: test/built-ins/Iterator/prototype/drop/return-is-forwarded', function (st) {
			var returnCount = 0;

			var makeBadIterator = function makeBadIterator() {
				return {
					next: function next() {
						return {
							done: false,
							value: 1
						};
					},
					'return': function () {
						returnCount += 1;
						return {};
					}
				};
			};

			var iter1 = drop(makeBadIterator(), 0);
			st.equal(returnCount, 0, 'iter1, before return()');
			iter1['return']();
			st.equal(returnCount, 1, 'iter1, after return()'); // TODO

			var iter2 = drop(makeBadIterator(), 1);
			st.equal(returnCount, 1, 'iter2, before return()'); // TODO
			iter2['return']();
			st.equal(returnCount, 2, 'iter2, after return()'); // TODO

			// 5 drops (i wish i had pipeline)
			var iter3 = drop(
				drop(
					drop(
						drop(
							drop(
								makeBadIterator(),
								1
							),
							1
						),
						1
					),
					1
				),
				1
			);
			st.equal(returnCount, 2, 'iter3, before return()'); // TODO
			iter3['return']();
			st.equal(returnCount, 3, 'iter3, after return()'); // TODO

			st.end();
		});

		t.test('262: test/built-ins/Iterator/prototype/drop/return-is-not-forwarded-after-exhaustion', { skip: !hasPropertyDescriptors }, function (st) {
			var makeBadIterator = function makeBadIterator() {
				return {
					next: function next() {
						return {
							done: true,
							value: undefined
						};
					},
					'return': function () {
						throw new SyntaxError();
					}
				};
			};

			var iter1 = drop(makeBadIterator(), 0); // TODO
			st['throws'](
				function () { iter1['return'](); },
				SyntaxError,
				'iter1, return() throws'
			);
			iter1.next();
			iter1['return']();

			var iter2 = drop(makeBadIterator(), 1);
			st['throws'](
				function () { iter2['return'](); },
				SyntaxError,
				'iter2, return() throws'
			);
			iter2.next();
			iter2['return']();

			// 5 drops (i wish i had pipeline)
			var iter3 = drop(
				drop(
					drop(
						drop(
							drop(
								makeBadIterator(),
								1
							),
							1
						),
						1
					),
					1
				),
				1
			);
			st['throws'](
				function () { iter3['return'](); },
				SyntaxError,
				'iter3, return() throws'
			);
			iter3.next();
			iter3['return']();

			var iter4 = drop(makeBadIterator(), 10);
			st['throws'](
				function () { iter4['return'](); },
				SyntaxError,
				'iter4, return() throws'
			);
			iter4.next();
			iter4['return']();

			st.end();
		});
	},
	index: function () {
		test('Iterator.prototype.' + fnName + ': index', function (t) {
			module.exports.tests(index, 'Iterator.prototype.' + fnName, t);

			t.test('polyfill has early-error IteratorClose', function (st) {
				var returnCalls = 0;
				var obj = {
					next: function () { return { done: true }; },
					'return': function () {
						returnCalls += 1;
						return { done: true };
					}
				};
				st['throws'](
					function () { index(obj, NaN); },
					RangeError,
					'polyfill throws RangeError for NaN limit'
				);
				st.equal(returnCalls, 1, 'polyfill calls return on early error');
				st.end();
			});

			t.end();
		});
	},
	implementation: function () {
		test('Iterator.prototype.' + fnName + ': implementation', function (t) {
			module.exports.tests(callBind(impl), 'Iterator.prototype.' + fnName, t);

			t.end();
		});
	},
	shimmed: function () {
		test('Iterator.prototype.' + fnName + ': shimmed', function (t) {
			t.test('Function name', { skip: !functionsHaveNames }, function (st) {
				st.equal(Iterator.prototype[fnName].name, fnName, 'Iterator#' + fnName + ' has name "' + fnName + '"');
				st.end();
			});

			t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) {
				et.equal(false, isEnumerable.call(Iterator.prototype, fnName), 'Iterator#' + fnName + ' is not enumerable');
				et.end();
			});

			t.test('bad string/this value', { skip: !hasStrictMode }, function (st) {
				st['throws'](function () { return Iterator.prototype[fnName].call(undefined, 'a'); }, TypeError, 'undefined is not an object');
				st['throws'](function () { return Iterator.prototype[fnName].call(null, 'a'); }, TypeError, 'null is not an object');
				st.end();
			});

			module.exports.tests(callBind(Iterator.prototype[fnName]), 'Iterator.prototype.' + fnName, t);

			t.end();
		});
	}
};
