package com.baoshi.swms.net.interceptor;

import android.text.TextUtils;
import android.util.Log;

import org.jetbrains.annotations.NotNull;

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

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * 请求Headers拦截器
 *
 * @author Zhendong Zhou
 * @date   2021/12/3 15:54
 */
public class HeaderInterceptor implements Interceptor {
    private final Map<String, String> params;

    public HeaderInterceptor(Map<String, String> p) {
        this.params = p;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request originalRequest = chain.request();
        //设置头部信息
        Request.Builder requestBuilder = originalRequest.newBuilder();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String value = entry.getValue();
                if (TextUtils.isEmpty(value) || "null".equals(value)) {
                    value = "";
                }
                requestBuilder.addHeader(entry.getKey(), value);
            }
        }
        requestBuilder.addHeader("Connection","close");
        requestBuilder.method(originalRequest.method(), originalRequest.body());
        Request request = requestBuilder.build();

        //TODO 打印请求信息，正式项目中可以注释掉
        /*RequestBody requestBody = request.body();
        String body = null;
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            body = buffer.readString(StandardCharsets.UTF_8);
        }
        Log.e("METHOD",request.method());
        Log.e("URL", String.valueOf(request.url()));
        Log.e("HEADERS", String.valueOf(request.headers()));
        Log.e("BODY","body:"+body);*/

        return chain.proceed(request);
    }
}