import {log4js} from "log4js/logger"
import {Context} from "./Context"

class Logger {

    isTraceEnabled(): boolean {
        return log4js.isTraceEnabled()
    }

    isDebugEnabled(): boolean {
        return log4js.isDebugEnabled()
    }

    isInfoEnabled(): boolean {
        return log4js.isInfoEnabled()
    }

    isWarnEnabled(): boolean {
        return log4js.isWarnEnabled()
    }

    isErrorEnabled(): boolean {
        return log4js.isErrorEnabled()
    }

    isFatalEnabled(): boolean {
        return log4js.isFatalEnabled()
    }

    trace(message: any, ...args: any) {
        log4js.trace(this.appendTraceId(message), ...args)
    }

    debug(message: any, ...args: any) {
        log4js.debug(this.appendTraceId(message), ...args)
    }

    info(message: any, ...args: any) {
        log4js.info(this.appendTraceId(message), ...args)
    }

    warn(message: any, ...args: any) {
        log4js.warn(this.appendTraceId(message), ...args)
    }

    error(message: any, ...args: any) {
        log4js.error(this.appendTraceId(message), ...args)
    }

    fatal(message: any, ...args: any) {
        log4js.fatal(this.appendTraceId(message), ...args)
    }

    mark(message: any, ...args: any) {
        log4js.mark(this.appendTraceId(message), ...args)
    }

    private appendTraceId(message: any) {
        const traceId = this.getTraceId();
        if (!traceId) {
            return message
        }
        const msg = message || '';
        return `  traceId:${traceId}  ${msg}`

    }

    private getTraceId() {
        const headers = Context.getRequestHeaders() || {}
        return headers['trace-id']
    }
}

const logger = new Logger()
export {logger}
