package cn.org.bjca.trust.push.di.interceptor;


import static java.nio.charset.StandardCharsets.UTF_8;

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

import cn.org.bjca.trust.push.common.LogHelper;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class LoggingInterceptor implements Interceptor {
    String TAG = "_____Http";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        ResponseBody responseBody = response.body();
        if (responseBody == null) {
            return response;
        }
        okhttp3.MediaType mediaType = responseBody.contentType();
        String content = response.body().string();
        LogHelper.e(request.toString(), TAG);
        LogHelper.e(response.code() + " : " + response.message(), TAG);
        String method = request.method();
        if ("POST".equals(method)) {
            Buffer buffer = new Buffer();
            try {
                request.body().writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = request.body().contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF_8);
                }
                String params = buffer.readString(charset);
                LogHelper.e(params, TAG);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LogHelper.d(content, TAG);
        LogHelper.e("耗时:  " + duration + "毫秒", TAG);
        return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();

    }
}