package com.qmth.boot.core.retrofit.interceptor;

import okhttp3.Interceptor;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.logging.LogLevel;

import java.io.IOException;

public class LoggingInterceptor implements Interceptor {

    private final static Logger log = LoggerFactory.getLogger(LoggingInterceptor.class);

    private HttpLoggingInterceptor httpLoggingInterceptor;

    public LoggingInterceptor(LogLevel logLevel) {
        this.httpLoggingInterceptor = new HttpLoggingInterceptor(getLogger(logLevel));
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        return httpLoggingInterceptor.intercept(chain);
    }

    public HttpLoggingInterceptor.Logger getLogger(LogLevel level) {
        switch (level) {
        case TRACE:
            return log::trace;
        case DEBUG:
            return log::debug;
        case INFO:
            return log::info;
        case WARN:
            return log::warn;
        case ERROR:
            return log::error;
        }
        throw new UnsupportedOperationException("Don't support this log level currently.");
    }
}
