package it.integry.integrywmsnative.core.rest;

import java.io.IOException;
import java.nio.charset.Charset;

import it.integry.integrywmsnative.core.utility.UtilityLogger;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by GiuseppeS on 06/03/2018.
 */

public class HttpLoggerInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        final Request request = chain.request();
        final HttpUrl url = request.url();

        UtilityLogger.info("Logging request: [" + url + "]");

        if (request.body() != null) {
            var buffer = new Buffer();
            request.body().writeTo(buffer);

            UtilityLogger.info(buffer.readUtf8());
        }

        var response = chain.proceed(chain.request());

        if (response.body() != null) {
            ResponseBody responseBody = response.body();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // request the entire body.
            Buffer buffer = source.getBuffer();
// clone buffer before reading from it
            String responseBodyString = buffer.clone().readString(Charset.forName("UTF-8"));
            UtilityLogger.info(responseBodyString);

        }

        return response;
    }
}
