'use strict';

var Mongoat = require('mongodb');
var connect = Mongoat.MongoClient.connect;
var hooks = {
  before: {},
  after: {}
};

Mongoat.Collection.prototype.insertTo = Mongoat.Collection.prototype.insert;

Mongoat.Collection.prototype.before = function(optName, callback) {
  if (hooks.before[optName] === undefined) {
    hooks.before[optName] = [];
  }

  var promisedCallback = function (query) {
    return new Promise(function(resolve, reject) {
      return resolve(callback(query));
    });
  };

  hooks.before[optName].push(promisedCallback);
};

Mongoat.Collection.prototype.after = function(optName, callback) {
  if (hooks.after[optName] === undefined) {
    hooks.after[optName] = [];
  }

  var promisedCallback = function (query) {
    return new Promise(function(resolve, reject) {
      return resolve(callback(query));
    });
  };

  hooks.after[optName].push(promisedCallback);
};

var promisify = function (array, document) {
  var promises = [];

  array.forEach(function (promisedCallback) {
    promises.push(promisedCallback(document));
  });

  return promises;
};

Mongoat.Collection.prototype.insert = function(document, options) {
  var promises = [];
  var _this = this;
  options = options || {};

  promises = promisify(hooks.before.insert, document);

  return Promise.all(promises).then(function (docToInsert) {
    return _this.insertTo(docToInsert[0], options).then(function (mongoObject) {
      promises = [];
      promises = promisify(hooks.after.insert, docToInsert[0]);
      Promise.all(promises);
      return mongoObject;
    });  
  });
};


module.exports = Mongoat;
@@ -42,16 +42,70 @@
 godb');%0A
+var utilsHelper = require('../helpers/utils-helper');%0A
 var conn
@@ -961,198 +961,8 @@
 %7D;%0A%0A
-var promisify = function (array, document) %7B%0A  var promises = %5B%5D;%0A%0A  array.forEach(function (promisedCallback) %7B%0A    promises.push(promisedCallback(document));%0A  %7D);%0A%0A  return promises;%0A%7D;%0A%0A
 Mong
@@ -1099,32 +1099,44 @@
 ;%0A%0A  promises = 
+utilsHelper.
 promisify(hooks.
@@ -1325,16 +1325,16 @@
 s = %5B%5D;%0A
-
       pr
@@ -1342,16 +1342,28 @@
 mises = 
+utilsHelper.
 promisif

Move promisify function to UtilsHelper object