var hubiquitus = require('hubiquitus-core');
var mongo = require('mongodb');

var db = null;
var conf = {};

exports.configure = function (properties, done) {
  conf.host = properties.host || '127.0.0.1';
  conf.port = properties.port || mongo.Connection.DEFAULT_PORT;
  conf.dbname = properties.dbname || 'hubiquitus';
  conf.collection = properties.collection || 'logs';
  conf.username = properties.username;
  conf.password = properties.password;

  var server = new mongo.Server(conf.host, conf.port, {auto_reconnect: true});
  var client = new mongo.MongoClient(server);
  client.open(function (err, client) {
    if (err) return (done && done(err));
    db = client.db(conf.dbname);

    if (conf.username) {
     db.authenticate(conf.username, conf.password, function (err, result) {
       if (err) return (done && done(err));
       if (result != true) return (done && done(new Error('authentication error')));
       overrideLogger();
       done && done();
     });
    } else {
      overrideLogger();
      done && done();
    }
  });
};

function overrideLogger() {
  hubiquitus.logger.log = function (namespace, level, messages) {
    db.collection(conf.collection, function (err, collection) {
      if (err) throw err;
      collection.insert({
        namespace: namespace,
        level: level,
        date: (new Date()).getTime(),
        messages: messages
      }, {w:0});
    });
  };
}

@@ -69,16 +69,71 @@
 ngodb');
+%0Avar _ = require('lodash');%0Avar util = require('util');
 %0A%0Avar db
@@ -1285,16 +1285,309 @@
 ow err;%0A
+      var processedMessages = %5B%5D;%0A      _.forEach(messages, function (message) %7B%0A        if (util.isError(message)) %7B%0A          processedMessages.push(%7Btype: 'Error', message: message.message, stack: message.stack%7D);%0A        %7D else %7B%0A          processedMessages.push(log);%0A        %7D%0A      %7D);%0A
       co
@@ -1604,16 +1604,16 @@
 nsert(%7B%0A
-
         
@@ -1712,17 +1712,26 @@
 ssages: 
-m
+processedM
 essages%0A

fix to properly log errors