'use strict';

var _ = require('underscore'),
	util = require('util'),
	colors = require('colors/safe');

/*
 * Borrowed from parking lib/node/utils/logger.js, thanks to @artzhuchka
 * TODO: should be separate nmp module
 */
module.exports = function() {
	function F(args) {
		return Logger.apply(this, args);
	}

	F.prototype = Logger.prototype;

	return new F(arguments);
};

module.exports.Logger = Logger;

var methodsHash = {
	log: colors.reset,
	info: colors.cyan,
	warn: colors.yellow,
	error: colors.red
};

function Logger(name, options) {
	this.name = name;
	this.options = _({dateTime: true}).extend(options);
	this._times = {};
}

Logger.prototype._colorizeArgs = function(argsColorFn, args) {
	return argsColorFn.call(colors, util.format.apply(util, args));
};

Logger.prototype._formatArgs = function(argsColorFn, args) {
	var parts = [];

	if (this.options.dateTime) {
		parts.push(colors.gray('[' + new Date().toUTCString() + ']'));
	}

	parts = parts.concat([
		colors.green('[' + this.name + ']'),
		this._colorizeArgs(argsColorFn, args)
	]);

	return parts.join(' ');
};

_(methodsHash).each(function(colorFn, method) {
	Logger.prototype[method] = function() {
		console.log.call(console, this._formatArgs(colorFn, arguments));
	};
});

Logger.prototype.trace = function(err) {
	console.log(this._colorizeArgs(colors.red, [err.stack || err]));
};

Logger.prototype.time = function() {
	this._times[util.format.apply(util, arguments)] = Date.now();
};

Logger.prototype.timeEnd = function() {
	var label = util.format.apply(util, arguments);
	var time = this._times[label];
	if (!time) return;
	this.log('%s: %dms', label, Date.now() - time);
};

@@ -1182,20 +1182,24 @@
 %09console
-.log
+%5Bmethod%5D
 .call(co
@@ -1291,14 +1291,201 @@
 ion(
-err
 ) %7B
+%0A%09var stack = _((new Error()).stack.split('%5Cn')).rest(2).join('%5Cn');%0A%09var msg = 'Trace';%0A%09if (arguments.length) %7B%0A%09%09msg += ': ' + util.format.apply(util, arguments);%0A%09%7D%0A%09msg += '%5Cn' + stack;
 %0A%09co
@@ -1496,32 +1496,30 @@
 e.log(this._
-colorize
+format
 Args(colors.
@@ -1528,25 +1528,100 @@
 d, %5B
-err.stack %7C%7C err%5D
+msg%5D));%0A%7D;%0A%0ALogger.prototype.dir = function() %7B%0A%09this.log(util.inspect.apply(util, arguments
 ));%0A
@@ -1916,13 +1916,12 @@
  - time);%0A%7D;
-%0A

update logger from upstream