'use strict';

var mongoose = require('mongoose');
var fs = require('fs');
var _ = require('lodash');
var Promise = require('bluebird');
var larAggregates = require('./laraggregates.js');

var config;

var env = process.env.NODE_ENV
if (env == 'test') {
    config = require('../config/test.json')
} else if (env == 'sandbox') {
    config = require('../config/sandbox.json');
} else if (env == 'dev' || env == 'development') {
    config = require('../config/development.json');
} else {
    config = require('../config/config.json');
}

var insertData = function(key, docs) {
    var deferred = Promise.defer();
    // Batch insert
    mongoose.model(key).collection.insert(docs, function(err, result) {
        if (err) {
            console.log('ERROR: could not insert data for ' + key);
            console.log(err);
            deferred.reject(err);
        } else {
            console.log('inserted '+result.length +' records for ' + key);
            deferred.resolve();
        }
    });
    return deferred.promise;
};

var uri = 'mongodb://' + config.mongoConfig.host + ':' + config.mongoConfig.port + '/' + (config.mongoConfig.database ? config.mongoConfig.database : 'hmda');
var opts = {};
if (config.mongoConfig.username) {
    opts.user = config.mongoConfig.username;
}
if (config.mongoConfig.password) {
    opts.pass = config.mongoConfig.password;
}
mongoose.connect(uri, opts);
mongoose.connection.on('error', console.error.bind(console, 'mongodb connection error:'));
mongoose.connection.once('open', function(callback) {
    console.log('dropping database..');
    mongoose.connection.db.executeDbCommand( {dropDatabase:1}, function(err, result) {
        if (err) {
            console.log(err);
            process.exit(-1);
        }
        // Kill the current connection, then re-establish it after we've dropped the db
        // so it will recreate it on connect
        mongoose.connection.close();
        mongoose.connect(uri, opts);
        mongoose.connection.on('error', console.error.bind(console, 'mongodb connection error:'));
        mongoose.connection.once('open', function(callback) {
            console.log('adding data..');

            // Load the mongoose models so they get created
            var models_path = __dirname + '/../models';
            fs.readdirSync(models_path).forEach(function (file) {
                require(models_path + '/' + file);
            });

            // Now loop through the loaded models
            Promise.map(_.keys(mongoose.connections[0].base.modelSchemas), function(key) {
                var docs;
                if (key.toLowerCase() === 'lar') {
                    return larAggregates.retrieveData()
                    .then(function(data) {
                        return insertData(key, data);
                    });
                } else {
                    var filename = key.toLowerCase()+'.json';
                    var lines = fs.readFileSync(__dirname + '/'+filename,'utf8').split('\n');
                    var docs =  lines.map(function(line) {
                        if (line) {
                            var data = JSON.parse(line);
                            delete data['_id'];
                            for (var prop in data) {
                                if (typeof data[prop] === 'object' && data[prop]['$date']!==undefined) {
                                    data[prop] = data[prop]['$date'];
                                }
                            }
                            return data;
                        } else {
                            return {};
                        }
                    });
                    return insertData(key, docs);
                }
            }, { concurrency: 10 })
            .then(function(result) {
                console.log('Done...');
                process.exit();
            });
        });
    });
});
@@ -225,16 +225,17 @@
 NODE_ENV
+;
 %0Aif (env
@@ -237,16 +237,17 @@
  (env ==
+=
  'test')
@@ -292,16 +292,17 @@
 t.json')
+;
 %0A%7D else 
@@ -311,16 +311,17 @@
  (env ==
+=
  'sandbo
@@ -387,24 +387,25 @@
 e if (env ==
+=
  'dev' %7C%7C en
@@ -408,16 +408,17 @@
 %7C env ==
+=
  'develo
@@ -617,31 +617,24 @@
 ();%0A
+%0A
     
-// Batch insert%0A   
+var batch =
  mon
@@ -667,19 +667,140 @@
 n.in
-sert(docs, 
+itializeOrderedBulkOp();%0A    _.each(docs, function(doc) %7B%0A        batch.insert(doc);%0A    %7D);%0A%0A    // Batch insert%0A    batch.execute(
 func
@@ -1026,24 +1026,30 @@
 ed '
-+
+ + 
 result.
-length
+nInserted
  +
+ 
 ' re
@@ -1734,18 +1734,9 @@
 .db.
-executeDbC
+c
 omma
@@ -1862,32 +1862,33 @@
 (-1);%0A        %7D%0A
+%0A
         // Kill 
@@ -2360,26 +2360,25 @@
   var models
-_p
+P
 ath = __dirn
@@ -2430,18 +2430,17 @@
 c(models
-_p
+P
 ath).for
@@ -2496,10 +2496,9 @@
 dels
-_p
+P
 ath 
@@ -3001,17 +3001,19 @@
 erCase()
-+
+ + 
 '.json';
@@ -3076,17 +3076,19 @@
 me + '/'
-+
+ + 
 filename
@@ -3088,16 +3088,17 @@
 ilename,
+ 
 'utf8').
@@ -3134,19 +3134,14 @@
     
-var 
 docs =
- 
  lin
@@ -3300,15 +3300,12 @@
 data
-%5B'
+.
 _id
-'%5D
 ;%0A  
@@ -3439,20 +3439,19 @@
 rop%5D
-%5B'
+.
 $date
-'%5D
+ 
 !==
+ 
 unde
@@ -3522,17 +3522,14 @@
 rop%5D
-%5B'
+.
 $date
-'%5D
 ;%0A  
@@ -4005,8 +4005,9 @@
  %7D);%0A%7D);
+%0A

Fix reload script for mongoose 4.x