package com.wisewoods.base.net;

import android.text.TextUtils;

import com.blankj.utilcode.util.JsonUtils;
import com.blankj.utilcode.util.LogUtils;

import org.jetbrains.annotations.NotNull;

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

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;

/**
 * 日志拦截
 */

public class LogInterceptor implements Interceptor {

    public static String TAG = "LogInterceptor";

    private boolean mEnableBody;

    public LogInterceptor() {
        this(false);
    }

    public LogInterceptor(boolean mEnableBody) {
        this.mEnableBody = mEnableBody;
    }

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

        StringBuilder sb = new StringBuilder("--> ");
        sb.append(request.method()).append(" ").append(request.url().toString());

        sb.append("\n");

        sb.append(request.headers().toString());

        //打印body
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            String requestBodyStr = buffer.readString(StandardCharsets.UTF_8);
            if (!TextUtils.isEmpty(requestBodyStr)) {
                sb.append(" ").append(requestBodyStr);
            }


        }
        sb.append("\n");

        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            sb.append("<-- HTTP FAILED: ").append(e.toString());
            LogUtils.dTag(TAG, sb.toString());
            throw e;
        }

        //打印response
        if (mEnableBody) {
            ResponseBody responseBody = response.body();
            if (null != responseBody) {
                Headers headers = response.headers();
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE);
                Buffer buffer = source.getBuffer();
                if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) {
                    GzipSource gzipSource = new GzipSource(buffer.clone());
                    buffer = new Buffer();
                    buffer.writeAll(gzipSource);
                    gzipSource.close();
                }

                String body = buffer.clone().readString(StandardCharsets.UTF_8);
                if (!TextUtils.isEmpty(body)) {
                    String formatJson = JsonUtils.formatJson(body, 1);
//                    if (formatJson.length() < 700) {
                    sb.append(formatJson);

//                    } else {
//                        sb.append(body);
//                    }
                } else {
                    sb.append("no body.");
                }
                sb.append("\n");
            }
        }

        //打印响应码
        sb.append("<-- ").append(response.code()).append(" ").append(response.message());
        LogUtils.dTag(TAG, sb.toString());

        return response;
    }

//    @Override
//    public okhttp3.Response intercept(Chain chain) throws IOException {
//        Request request = chain.request();
//        long startTime = System.currentTimeMillis();
//        okhttp3.Response response = chain.proceed(chain.request());
//        long endTime = System.currentTimeMillis();
//        long duration=endTime-startTime;
//        okhttp3.MediaType mediaType = response.body().contentType();
//        String content = response.body().string();
//        Log.d(TAG,"\n");
//        Log.d(TAG,"----------Start----------------");
//        Log.d(TAG, "| "+request.toString());
//        String method=request.method();
//        if("POST".equals(method)){
//            StringBuilder sb = new StringBuilder();
//            if (request.body() instanceof FormBody) {
//                FormBody body = (FormBody) request.body();
//                for (int i = 0; i < body.size(); i++) {
//                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
//                }
//                sb.delete(sb.length() - 1, sb.length());
//                Log.d(TAG, "| RequestParams:{"+sb.toString()+"}");
//            }
//        }
//        Log.d(TAG, "| Response:" + content);
//        Log.d(TAG,"----------End:"+duration+"毫秒----------");
//        return response.newBuilder()
//                .body(okhttp3.ResponseBody.create(mediaType, content))
//                .build();
//    }
}

