package org.akapps.rest.logging;

/**
 * Logger implementation based on "slf4j". Adapter for {@link org.slf4j.Logger}.
 *
 * @author Antoine Kapps
 */
class Slf4jLogger implements Logger {

    private final org.slf4j.Logger wrapped;

    Slf4jLogger(org.slf4j.Logger wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public boolean isDebugEnabled() {
        return wrapped.isDebugEnabled();
    }

    @Override
    public void debug(String message, Object... params) {
        wrapped.debug(message, params);
    }

    @Override
    public void debug(Throwable thrown, String message, Object... params) {
        if (wrapped.isDebugEnabled()) {
            wrapped.debug(formatMessage(message, params), thrown);
        }
    }

    @Override
    public boolean isInfoEnabled() {
        return wrapped.isInfoEnabled();
    }

    @Override
    public void info(String message, Object... params) {
        wrapped.info(message, params);
    }

    @Override
    public void info(Throwable thrown, String message, Object... params) {
        if (wrapped.isInfoEnabled()) {
            wrapped.info(formatMessage(message, params), thrown);
        }
    }

    @Override
    public boolean isWarnEnabled() {
        return wrapped.isWarnEnabled();
    }

    @Override
    public void warn(String message, Object... params) {
        wrapped.warn(message, params);
    }

    @Override
    public void warn(Throwable thrown, String message, Object... params) {
        if (wrapped.isWarnEnabled()) {
            wrapped.warn(formatMessage(message, params), thrown);
        }
    }

    @Override
    public boolean isErrorEnabled() {
        return wrapped.isErrorEnabled();
    }

    @Override
    public void error(String message, Object... params) {
        wrapped.error(message, params);
    }

    @Override
    public void error(Throwable thrown, String message, Object... params) {
        if (wrapped.isErrorEnabled()) {
            wrapped.error(formatMessage(message, params), thrown);
        }
    }

    private String formatMessage(String message, Object[] params) {
        if (params.length == 0)
            return message;

        try {
            return JulLogger.constructMessage(message, params);
        } catch (Exception e) {
            wrapped.error("Exception while formatting message [\"" + message + "\"]", e);
            return message;
        }
    }
}
