/**
 * Setup and Teardown Adapter Normalization
 */

var _ = require('lodash'),
    async = require('async');

module.exports = {

  // Logic to handle the (re)instantiation of collections
  registerCollection: function(cb) {
    var self = this;

    // Call registerCollection on each adapter this collection uses
    function register(item, cb) {
      if(item.registerCollection) {

        // Remove hasMany association keys before sending down to adapter
        var schema = _.clone(self.query._schema.schema);

        Object.keys(schema).forEach(function(key) {
          if(schema[key].type) return;
          delete schema[key];
        });

        // Merge Collection Identity with adapter def
        var collection = {
          config: _.clone(item).config,
          definition: schema,
          identity: self.collection
        };

        return item.registerCollection(collection, cb);
      }

      cb();
    }

    async.each(this.adapterDefs, register, function(err) {
      if(err) return cb(err);
      cb();
    });

  },

  // Teardown is fired once-per-adapter
  // Should tear down any open connections, etc. for each collection
  // (i.e. tear down any remaining connections to the underlying data model)
  // (i.e. flush data to disk before the adapter shuts down)
  teardown: function(cb) {
    if (this.adapter.teardown)
      return this.adapter.teardown.apply(this, arguments);

    cb();
  }

};

@@ -101,16 +101,107 @@
 'async')
+,%0A    utils = require('../utils/helpers'),%0A    hasOwnProperty = utils.object.hasOwnProperty
 ;%0A%0Amodul
@@ -443,21 +443,38 @@
      if(
+hasOwnProperty(
 item
-.
+, '
 register
@@ -483,16 +483,18 @@
 llection
+')
 ) %7B%0A%0A   
@@ -687,16 +687,31 @@
      if(
+hasOwnProperty(
 schema%5Bk
@@ -717,13 +717,17 @@
 key%5D
-.
+, '
 type
+')
 ) re
@@ -771,24 +771,270 @@
        %7D);%0A%0A
+        // Grab JunctionTable flag%0A        var meta = %7B%7D;%0A        meta.junctionTable = hasOwnProperty(self.query.waterline.schema%5Bself.collection%5D, 'junctionTable') ?%0A          self.query.waterline.schema%5Bself.collection%5D.junctionTable : false;%0A%0A
         // M
@@ -1207,16 +1207,38 @@
 llection
+,%0A          meta: meta
 %0A       

append meta information to schemas flagging a junctionTable