package com.rc.httpcore.interceptor

import android.util.Log
import okhttp3.*
import okio.Buffer
import org.json.JSONObject

class NullToEmptyInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val modifiedRequest = modifyRequest(request)

        // 打印请求日志
        printRequestLog(modifiedRequest)

        val response = chain.proceed(modifiedRequest)

        // 打印响应日志
        printResponseLog(response)
        return response
    }

    private fun modifyRequest(request: Request): Request {
        // 获取原始的请求体
        val originalBody = request.body() ?: return request

        // 读取原始的 JSON 数据
        val buffer = Buffer()
        originalBody.writeTo(buffer)
        val originalJsonString = buffer.readUtf8()
        println("<-- End response1$originalJsonString")
        // 将原始 JSON 数据转换为 JSONObject
        val jsonObject = JSONObject(originalJsonString)
        println("<-- End response2$jsonObject")
        // 遍历 JSON 对象的键，将值为 null 的键替换成空字符串
        val keys = jsonObject.keys()
        while (keys.hasNext()) {
            val key = keys.next()
            println("<-- End response3$key")
            if (jsonObject.isNull(key)) {
                jsonObject.put(key, "")
            }
        }

        // 构建修改后的请求体
        val modifiedJsonString = jsonObject.toString()
        val mediaType = MediaType.parse("application/json")
        val modifiedBody = RequestBody.create(mediaType, modifiedJsonString)

        // 构建修改后的请求
        return request.newBuilder()
            .method(request.method(), modifiedBody)
            .build()
    }


    private fun printRequestLog(request: Request) {
        println("--> Sending request to ${request.url()}")
        println("Headers: ${request.headers()}")
        println("Method: ${request.method()}")
        println("Body: ${bodyToString(request.body())}")
        println("--> End request")
    }

    private fun printResponseLog(response: Response) {
        println("<-- Received response for ${response.request().url()}")
        println("Code: ${response.code()}")
        println("Message: ${response.message()}")
        println("Headers: ${response.headers()}")
        println("Body: ${bodyToString(response.peekBody(Long.MAX_VALUE).string())}")
        println("<-- End response")
    }

    private fun bodyToString(body: RequestBody?): String {
        return try {
            val buffer = Buffer()
            body?.writeTo(buffer)
            buffer.readUtf8()
        } catch (e: Exception) {
            "Error parsing body: ${e.message}"
        }
    }

    private fun bodyToString(body: String): String {
        // Limit the output to a reasonable length
        val maxLength = 4000
        return if (body.length > maxLength) {
            body.substring(0, maxLength) + "...(truncated)"
        } else {
            body
        }
    }

}