'use strict';

const util = require('util');
const path = require('path');
const winston = require('winston');

require('winston-daily-rotate-file');

const args = require('./argv');

function logger(filepath) {
    const root = filepath.match(/src\/|dist\//);
    const filename = filepath.slice(root.index + root[0].length)
        .replace(path.extname(filepath), '');

    return winston.createLogger({
        format: winston.format.combine(
            winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
            winston.format(info => (info instanceof Error
                ? { ...info, message: info.stack }
                : { ...info, message: typeof info.message === 'string' ? info.message : util.inspect(info.message) }))(),
            winston.format.colorize(),
            winston.format.printf(({ level, timestamp, label, message }) => `${timestamp} ${level} [${label || filename}] ${message}`),
        ),
        transports: [
            new winston.transports.Console({
                level: args.level,
                timestamp: true,
            }),
            new winston.transports.DailyRotateFile({
                datePattern: 'YYYY-MM-DD',
                filename: 'log/%DATE%.log',
                level: 'silly',
            }),
        ],
    });
}

module.exports = logger;
