/**
* Module to seed a database.
* 
* @todo re-write to use async to reduce the nested function, and quit on completion
* @todo make model loading more effecient
*
*/

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    async = require('async'),
    _ = require('underscore'),
    fs = require('fs');


/**
* Bootstrap our models
* @note this is the same code as found in server.js
* 
* @todo we can combine the models require and definintion (below) into one function. 
*
*/
var models_path = __dirname + '/app/models';
fs.readdirSync(models_path).forEach(function(file) {
    require(models_path + '/' + file);
});


// Saving in array allows us to call below in doSeed function.
var models = {};
models.Quote = mongoose.model('Quote');
models.Application = mongoose.model('Application');
models.User = mongoose.model('User');
models.Vendor = mongoose.model('Vendor');
models.Program = mongoose.model('Program');


/**
* Get our seed data
* @note again this is not the most elegant, we should be doing something
* more automated based on model files... ie: check if seed data exists then add it to our array
*
* @note we sould include some type of functionality to automatically pluralize / depluralize names
*
*/
var resources = {};
resources.Vendor        = require('./seed_data/vendor').seed();
resources.Program       = require('./seed_data/program').seed();
resources.Application   = require('./seed_data/application').seed();
resources.Quote         = require('./seed_data/quote').seed();
resources.User          = require('./seed_data/user').seed();


/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */
var env = process.env.NODE_ENV || 'development',
    config = require('./config/config')[env],
    mongoose = require('mongoose');
    
// create database connection
var db = mongoose.connect(config.db, function() {
    console.log('Connected to ' + env + ' database!');
    
    // drop the existing database
    // @todo when using mongolab these drops the users!!! so then we can't connect back
    // @refactor to drop all collections except users? Or connect with a master user
    db.connection.db.dropDatabase(function() {
        console.log('Database dropped');
        
        // close our connnection
        db.connection.close(function(){
            console.log('Database connection closed, re-opening now...');
            
            // reconnect
            db = mongoose.connect(config.db, function() {
                console.log('Re-connected, beginning seed');
                doSeed();
                
            });
            
        });
   
    });
    
});


/**
* Function to do the actual seed. Will be called once database is dropped, 
* and the connection is closed and re-opened.
*
*/
var doSeed = function() {
    
    // loop through resources
    _.each(resources, function(value, key) {
        
        console.log('Seeding ' + key + ' collection');
        
        // loop through our resource items
        _.each(value, function(contents) {
            
            // carete new Mongoose object
            var item = new models[key](contents);
            
            // save object
            item.save(function(err, data) {
                if(err) throw(err);
                console.log(key + ' ' + item._id + ' created.');
            }); 
            
        });

    });
    
};
@@ -310,24 +310,59 @@
 uire('fs');%0A
+    %0Avar async = require('async');%0A
 %0A%0A/**%0A* Boot
@@ -1284,16 +1284,78 @@
 s = %7B%7D;%0A
+resources.User          = require('./seed_data/user').seed();%0A
 resource
@@ -1611,70 +1611,8 @@
 ();%0A
-resources.User          = require('./seed_data/user').seed();%0A
 %0A%0A/*
@@ -2853,24 +2853,53 @@
 on() %7B%0A    %0A
+    var needsSeed = %5B%5D;%0A    %0A
     // loop 
@@ -3225,37 +3225,83 @@
 tents);%0A        
+%0A
     
-%0A
+        var doThis = function(callback) %7B%0A    
             // s
@@ -3323,16 +3323,20 @@
         
+  
+  
 item.sav
@@ -3355,24 +3355,28 @@
 rr, data) %7B%0A
+    
             
@@ -3407,32 +3407,36 @@
                 
+    
 console.log(key 
@@ -3484,44 +3484,178 @@
     
-%7D); %0A            %0A        %7D);%0A%0A    %7D
+        callback(null, item);%0A                %7D); %0A            %7D;%0A            %0A            needsSeed.push(doThis);%0A  %0A        %7D);%0A%0A    %7D);%0A    %0A    async.series(needsSeed
 );%0A 

Fix seed function to run async. This fixes issues where content needs to be seeded in order to prevent errors. (i.e.: users before user references)