'use strict';

// sets up the logging object using the Winston logging library

const winston = require('winston');
const WinstonLogStash = require('winston3-logstash-transport');
const { transports, format } = require('winston');
const { combine } = format;

var moment = require('moment');
var conf = require('../configLoader/LogConfig.js');
var UtilValidation = require('../../shared/utils/UtilValidation');
var log = conf.get('log');

var createTransport = function(loggerName, fileName){
    var ret = [];

    if (UtilValidation.hasValue(fileName)){
        ret.push(new transports.File({
            name: loggerName,
            filename: fileName,
            level: log.level,
            json: false,
            maxsize: log.maxSize,
            maxFiles: log.maxFileCount,
            tailable: true
        }));
    }

    if (log.logStash) {
        ret.push(new WinstonLogStash(log.logStash));
    }

    if (log.enableConsole){
        ret.push(new transports.Console({
            name:'log-console-main',
            level: log.level,
            json: false
        }));
    }

    return ret;
};

const createFormat = () => {
    return combine(
        format.printf(info =>
            moment().format(conf.dateFormat) + ` - ${info.level} PID-` + process.pid + ` ${info.message}`
            +` ${info.meta ? '\n\t' + info.meta : ''}`
        )
    );
};

winston.loggers.add('main', {
    format: createFormat(),
    transports: createTransport('log-file-main', log.main)
});

winston.loggers.add('db', {
    format: createFormat(),
    transports: createTransport('log-file-db', log.db)
});

winston.loggers.add('ftSearch', {
    format: createFormat(),
    transports: createTransport('log-file-search', log.ftSearch)
});

winston.loggers.add('test', {
    format: createFormat(),
    transports: createTransport('log-file-test', log.test)
});

winston.loggers.add('auth', {
    format: createFormat(),
    transports: createTransport('log-file-auth', log.auth)
});

winston.loggers.add('webAppError', {
    format: createFormat(),
    transports: createTransport('log-file-web-app', log.webAppError)
});

module.exports = winston;