package com.ruansee.macall.testwebview.app;

import android.net.Uri;

import androidx.annotation.NonNull;

import com.rs.macall.androidx.basemodel.utils.StringUtil;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.platform.Platform;
import okio.Buffer;
import okio.BufferedSource;

import static okhttp3.internal.platform.Platform.INFO;

public class HttpLoggingInterceptor implements Interceptor {

    private static final Charset UTF8 = Charset.forName("UTF-8");

    private Map<String, String> headers;

    public enum Level {
        /**
         * No logs.
         */
        NONE,
        /**
         * Logs request and response lines.
         *
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/ic_btn_compare_mode.ic_btn_compare_mode (ic_tv_left_house-byte body)
         *
         * <-- 200 OK (22ms, 6-byte body)
         * }</pre>
         */
        BASIC,
        /**
         * Logs request and response lines and their respective headers.
         *
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/ic_btn_compare_mode.ic_btn_compare_mode
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: ic_tv_left_house
         * --> END POST
         *
         * <-- 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         * <-- END HTTP
         * }</pre>
         */
        HEADERS,
        /**
         * Logs request and response lines and their respective headers and bodies (if present).
         *
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/ic_btn_compare_mode.ic_btn_compare_mode
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: ic_tv_left_house
         *
         * Hi?
         * --> END POST
         *
         * <-- 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         *
         * Hello!
         * <-- END HTTP
         * }</pre>
         */
        BODY
    }

    public interface Logger {
        void log(String message);

        /**
         *
         */
        Logger DEFAULT = new Logger() {
            @Override
            public void log(String message) {
                Platform.get().log(message, INFO, null);
            }
        };
    }

    public HttpLoggingInterceptor() {
        this(Logger.DEFAULT);
    }

    /**
     * 设置请求Header
     *
     * @param headers header 集合
     */
    public HttpLoggingInterceptor(Map<String, String> headers) {
        this(Logger.DEFAULT);
        this.headers = headers;
    }

    public HttpLoggingInterceptor(Logger logger) {
        this.logger = logger;
    }

    private final Logger logger;
    private volatile Level level = Level.BODY;

    private void log(String msg){
        if (RuanseeApp.isPrintLog){
            logger.log(msg);
        }
    }

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        //  在这里设置公共的Header
        Request requestS = chain.request();
        Request.Builder requestBuilder = requestS.newBuilder();
//        if (StringUtil.hasContent(RuanseeApplication.getAppCache().getSystem_token())) {
//            String heard = "Bearer " + RuanseeApplication.getAppCache().getSystem_token();
//        }
//        if (StringUtil.isNullOrEmpty(RuanseeApplication.getAppCache().getUserInfo())){
//            String s = Base64.encodeBase64String(RuanseeApplication.getUserData().toJson().getBytes());
//            RuanseeApplication.getAppCache().setUserInfo(s);
//        }
//        requestBuilder.addHeader("userInfo", RuanseeApplication.getAppCache().getUserInfo());
//        String se = requestS.url().toString();
//        if (StringUtil.hasContent(se)) {
//            if (!se.endsWith(".jpg") && !se.endsWith(".png")&&!se.contains("wzt")){
//                    se = se.replace("http://" + RuanseeApplication.getAppCache().getIp() + ":8081/", RuanseeApplication.getAppCache().getBaseUrlPath());
//            }
//            if (!se.endsWith(".jpg") && !se.endsWith(".png")&&!se.contains("wzt_api_out")){
//                    se = se.replace("http://" + RuanseeApplication.getAppCache().getIp() + "/", RuanseeApplication.getAppCache().getBaseUrlPath());
//            }
//            requestBuilder.url(se);
//        }
        //在这里设置公共的Header
        Level level = this.level;

        Request request = requestBuilder.build();

//        Request request = chain.request();
        if (level == Level.NONE) {
            return chain.proceed(request);
        }

        boolean logBody = level == Level.BODY;
        boolean logHeaders = logBody || level == Level.HEADERS;

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        Connection connection = chain.connection();
        String requestStartMessage = "--> "
                + request.method()
                + ' ' + request.url()
                + (connection != null ? " " + connection.protocol() : "");
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        log(requestStartMessage);

        if (logHeaders) {
            if (hasRequestBody) {
                // Request body headers are only present when installed as a network interceptor. Force
                // them to be included (when available) so there values are known.
                if (requestBody.contentType() != null) {
                    log("Content-Type: " + requestBody.contentType());
                }
                if (requestBody.contentLength() != -1) {
                    log("Content-Length: " + requestBody.contentLength());
                }
            }

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                log("Headers.name: " + headers.name(i) + ", Header.value: " + headers.value(i));
            }

            if (!logBody || !hasRequestBody) {
                log("--> END " + request.method());
            } else if (bodyEncoded(request.headers())) {
                log("--> END " + request.method() + " (encoded body omitted)");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);

                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }

                log("");
                if (isPlaintext(buffer)) {
                    log(buffer.readString(charset));
                    log("--> END " + request.method()
                            + " (" + requestBody.contentLength() + "-byte body)");
                } else {
                    log("--> END " + request.method() + " (binary "
                            + requestBody.contentLength() + "-byte body omitted)");
                }
            }
        }

        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            log("<-- HTTP FAILED: " + e);
            throw e;
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        log("<-- response.code->"
                + response.code()
                + (response.message().isEmpty() ? "" : ' ' + response.message())
                + ' ' + response.request().url()
                + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');

        if (logHeaders) {
            Headers headers = response.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                log("Headers: " + headers.name(i) + " = " + Uri.decode(headers.value(i)));
            }
            if (!logBody || !HttpHeaders.hasBody(response)) {
                log("<-- END HTTP");
            } else if (bodyEncoded(response.headers())) {
                log("<-- END HTTP (encoded body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();
                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                if (!isPlaintext(buffer)) {
                    log("");
                    log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                    return response;
                }
                if (contentLength != 0) {
                    log("");
                    log(buffer.clone().readString(charset));
                }
                log("<-- END HTTP (" + buffer.size() + "-byte body)");
            }
        }
        return response;
    }

    private static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }
}
