import FileRotateTransport from "winston-daily-rotate-file";
import winston from "winston";
import moment from "moment";
import _ from 'underscore';

// console.log("Setting up logging....");

let production = (process.env.NODE_ENV === "production");
let logPath = process.env.LOG_PATH;

let fileTransport = logPath ? new FileRotateTransport({
	format: winston.format.combine(
		winston.format.simple(),
		winston.format.printf((info) => {
			return moment(info.timestamp).format('YYYY-MM-DD hh:mm:ss SSSS') + " " + info.message;
		})
	),
	auditFile: "audit.json",
	maxSize: '1m',
	maxFiles: 20,
	dirname: logPath,
	filename: 'DistrictCentral-%DATE%.log',
	dateFormat: "YYYY-MM-DD"
}) : null;
let consoleColorTransport = new winston.transports.Console({
	format: winston.format.combine(
		winston.format.cli()
	),
});
let consoleTransport = new winston.transports.Console({
	format: winston.format.combine(
		winston.format.simple()
	),
});
let transports = production ? (logPath ? [fileTransport] : [consoleTransport]) : (logPath ? [fileTransport, consoleColorTransport] : [consoleColorTransport]);
//let transports = [fileTransport, consoleTransport];

//TODO: Use GrayLog or SysLog and interface with a log server.

/* Use GrayLog2 Transport
const Graylog2 = require('winston-graylog2');
logger.add(new Graylog2(options));
 */

/* Use Syslog Transport
npm install winston-syslog
  const winston = require('winston');

  //
  // Requiring `winston-syslog` will expose
  // `winston.transports.Syslog`
  //
  require('winston-syslog').Syslog;

  winston.add(new winston.transports.Syslog(options));
 */

// Setup the logger.
let logger = winston.createLogger({
	level: production ? 'info' : 'silly',
	// format: winston.format.combine(
	// 	winston.format.timestamp({format: 'YYYY-MM-DD hh:mm:ss SSSS'})
	// ),
	format: winston.format(function(info) {
		//Add a timestamp to the info structure.
		info.timestamp = new Date();

		return info;
	})(),
	defaultMeta: {app: 'DistrictCentral'},
	transports: transports
});

let consoleLogOriginal = console.log;

// Override the log and error functions.
console.log = function(d) {
	// For some reason Meteor requires the original console.log for the initial listening log output.  If that isn't performed then Meteor never starts properly.
	if(arguments.length === 1 && arguments[0] === 'LISTENING') {
		return consoleLogOriginal.call(console, 'LISTENING');
	}
	else logger.log("debug", _.isObject(d) ? JSON.stringify(d) : d);
}
console.info = function(d) {
	logger.log("info", _.isObject(d) ? JSON.stringify(d) : d);
}
console.warn = function(d) {
	logger.log("warn", _.isObject(d) ? JSON.stringify(d) : d);
}
console.error = function(e) {
	logger.log("error", e.stack || e);
}

// console.log("Logger setup.");