package com.gamedog.vididin.core.network.di


import android.util.Log
import com.ama.core.architecture.util.AndroidUtil
import com.ama.core.architecture.util.DeviceUtil
import com.gamedog.vididin.request.RequestUtil
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.asResponseBody
import okio.Buffer
import java.io.IOException
import java.util.Locale


class GlobalInterceptor2 : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val bodyStr = readBody(chain.request().body)
        val emptyBody = "{}".toRequestBody("application/json;charset=utf-8".toMediaType())
        val requestBody = if (bodyStr.isNotBlank()) request.body else emptyBody



        val requestBuilder = chain.request().newBuilder()
            .addHeader("User-Agent", "Android")
            .addHeader("Accept-Language", Locale.getDefault().toLanguageTag())
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .addHeader("Accept-Charset", "utf-8")
            // server real defined
            .addHeader("ApplicationId", AndroidUtil.getPackageId())
            .addHeader("DeviceId", DeviceUtil.generateDeviceId())
            .addHeader("authorazation", "Bearer xxxxx")

        request = requestBuilder.build()

        val response = chain.proceed(request)


        if (true) {
            try {
                val contentStr = clone(response.body)?.string()
                Log.d("RetroLog" ,
                    """
                    ———————————————— 请求 Start ——————————————————————————————
                    ${request.url} 
                    ******** 请求头 ${request.method} ********：
                    ${getRequestHeadersString(request)}
                    ******** 请求体(当post等时) ********：
                    ${readBody(requestBody)}
                    ******** 请求响应 ********：
                    $contentStr
                    ————————————————  请求 End ———————————————————————————————
                """.trimIndent()
                )
            } catch (e: Exception) {
                Log.d("RetroLog" , "GlobalInterceptor request.exception : ${e.localizedMessage}}")
            }
        }

        return response
    }


    fun getRequestHeadersString(request: Request): String {
        val headers = request.headers
        val headerCount = headers.size

        val sb = StringBuilder()
        for (i in 0 until headerCount) {
            val key = headers.name(i)
            val value = headers.value(i)
            sb.append("$key=$value\n")
        }
        return sb.toString()
    }

    private fun readBody(body: RequestBody?): String {
        val buffer = Buffer()
        body?.writeTo(buffer)
        return buffer.readUtf8()
    }

    @Throws(IOException::class)
    private fun clone(body: ResponseBody?): ResponseBody? {
        val source = body?.source()
        if (source?.request(Long.MAX_VALUE) == true) throw IOException("body too long!")
        val bufferedCopy = source?.buffer?.clone()
        return bufferedCopy?.asResponseBody(body.contentType(), body.contentLength())
    }
}