package com.xuqm.base.di.interceptor;


import com.xuqm.base.common.LogHelper;

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

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

import static okhttp3.internal.Util.UTF_8;

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(TAG, request.toString());
        LogHelper.e(TAG, response.code() + " : " + response.message());
        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(TAG, params);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LogHelper.json(TAG, content);
        LogHelper.e(TAG, "耗时:  " + duration + "毫秒");
        return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();

    }
}