package com.mogo.cloud.network.interceptor

import android.util.Log
import com.mogo.cloud.network.NetConstants.Companion.TAG
import com.mogo.cloud.passport.MoGoAiCloudClientConfig
import okhttp3.*
import okio.Buffer
import java.io.IOException
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

/**
 * created by wujifei on 2021/1/27 14:33
 * describe:网络日志拦截
 */
class HttpLoggingInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val requestBody = request.body()
        val hasRequestBody = requestBody != null
        var protocol = Protocol.HTTP_1_1.toString()
        var body = "null"
        if (chain.connection() != null && chain.connection()!!.protocol() != null) {
            protocol = chain.connection()!!.protocol().toString()
        }

        if (hasRequestBody) {
            try {
                val UTF8 = Charset.forName("UTF-8")
                val buffer = Buffer()
                requestBody?.writeTo(buffer)
                var charset = UTF8
                val contentType = requestBody?.contentType()
                if (contentType != null) {
                    charset = contentType.charset(UTF8)
                }
                if (charset != null) {
                    body = buffer.readString(charset)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        val logMsg = StringBuilder()
            .append("------> http request start").append("\r\n")
            .append(protocol).append(", ")
            .append(request.method()).append("\r\n")
            .append("Request Headers: {").append(request.headers().toString().replace("\n", ", "))
            .append("}\r\n")
            .append("Url: ").append(request.url()).append("\r\n")
            .append("Content-Type: ").append(requestBody?.contentType()).append("\r\n")
            .append("Content-Length: ").append(requestBody?.contentLength()).append("\r\n")
            .append("Content-body: ").append(body).append("\r\n")
            .append("------> http request end").append("\r\n").append("\r\n")


        val startTime = System.nanoTime()
        val response = chain.proceed(chain.request())
        val endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)

        val responseBody = response.body()
        var responseContent: String? = null
        var bodySize: String? = null
        var contentType: MediaType? = null
        var consumedResponse = false

        if (responseBody != null) {
            val contentLength = responseBody.contentLength()
            bodySize = if (contentLength != -1L) "$contentLength-byte" else "unknown-length"
            contentType = responseBody.contentType()
            responseContent = responseBody.string()
            consumedResponse = true
        }

        logMsg.append("------> http response start").append("\r\n")
            .append(response.code()).append(" ")
            .append(response.message()).append(" ")
            .append(response.protocol()).append(" ").append("\r\n")
            .append("Response Content: ").append(responseContent).append("\r\n")
            .append("Content-Type: ").append(contentType).append("\r\n")
            .append("Content-Length: ").append(bodySize).append("\r\n")
            .append("Time: (").append(endTime).append("ms)").append("\r\n")
            .append("------> http response end")
        if (response.code() != 200) {
            Log.e(TAG, logMsg.toString())
        } else {
            if (MoGoAiCloudClientConfig.getInstance().isShowNetDebugLog) {
                Log.d(TAG, logMsg.toString())
            }
        }
        return if (consumedResponse) response.newBuilder()
            .body(ResponseBody.create(contentType, responseContent)).build() else response

    }
}