'use strict';

var seqCollectionName = '__sequences';

module.exports = function(collection) {
	var db = collection.s.db,
		Collection = require('../mongodbext').Collection,
		seqCollection = new Collection(db, seqCollectionName);

	var ensureSequenceCollection = function(callback) {
		db.collections(function(err, collectionNames) {
			if (err) return callback(err);

			if (collectionNames.indexOf(seqCollectionName) === -1) {
				// process error when index already existing
				seqCollection.createIndex({
					name: 1
				}, {unique: true}, callback);
			} else {
				callback();
			}
		});
	};

	var getCurrentAndIncreaseId = function(incValue, callback) {
		seqCollection.findOneAndUpsert({
			name: collection.collectionName
		}, {
			$inc: {
				value: incValue
			}
		}, function(err, sequence) {
			if (err) return callback(err);

			callback(null, sequence ? sequence.value : 0);
		});
	};

	var addId = function(params, callback) {
		var objs = params.obj || params.objs;
		if (!Array.isArray(objs)) {
			objs = [objs];
		}

		// find objs without _id
		var addIdObjs = objs.filter(function(obj) {
			return !('_id' in obj);
		});

		if (addIdObjs.length) {
			ensureSequenceCollection(function(err) {
				if (err) return callback();

				getCurrentAndIncreaseId(addIdObjs.length, function(err, currentId) {
					if (err) return callback(err);

					// add id to each object
					addIdObjs.forEach(function(obj) {
						obj._id = ++currentId;
					});

					callback();
				});
			});
		} else {
			callback();
		}
	};

	collection.on('beforeInsertOne', addId);

	collection.on('beforeInsertMany', addId);
};

@@ -12,74 +12,197 @@
 ';%0A%0A
-var seqCollectionName = '__sequences';%0A%0Amodule.exports = fun
+module.exports = function(collection, options) %7B%0A%09options = options %7C%7C %7B%7D;%0A%09var seqCollectionName = options.seqCollectionName %7C%7C '__sequences';%0A%09var seqName = options.seqName %7C%7C colle
 ction
-(
+.
 coll
@@ -207,19 +207,55 @@
 llection
-) %7B
+Name;%0A%09var key = options.key %7C%7C '_id';%0A
 %0A%09var db
@@ -761,32 +761,37 @@
 %0A%09var getCurrent
+Value
 AndIncreaseId = 
@@ -785,18 +785,16 @@
 Increase
-Id
  = funct
@@ -863,37 +863,19 @@
 %09%09name: 
-collection.collection
+seq
 Name%0A%09%09%7D
@@ -1199,19 +1199,19 @@
 without 
-_id
+key
 %0A%09%09var a
@@ -1261,21 +1261,19 @@
 eturn !(
-'_id'
+key
  in obj)
@@ -1398,16 +1398,21 @@
 tCurrent
+Value
 AndIncre
@@ -1414,18 +1414,16 @@
 Increase
-Id
 (addIdOb
@@ -1454,18 +1454,21 @@
  current
-Id
+Value
 ) %7B%0A%09%09%09%09
@@ -1582,12 +1582,13 @@
 %09obj
-._id
+%5Bkey%5D
  = +
@@ -1595,18 +1595,21 @@
 +current
-Id
+Value
 ;%0A%09%09%09%09%09%7D

add options to sequence plugin