package com.remax.visualnovel.api.interceptor


import com.remax.visualnovel.BuildConfig
import com.remax.visualnovel.constant.AppConstant
import com.remax.visualnovel.manager.login.LoginManager
import com.remax.visualnovel.utils.AppUtils
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.asResponseBody
import okio.Buffer
import timber.log.Timber
import java.io.IOException

/**
 * Created by HJW on 2022/10/17
 */
class GlobalInterceptor : 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 platform = "ANDROID_${BuildConfig.VERSION_NAME}"
//        val userAgent =  String.format(
//            "E-Pal/%s (%s; android %s)",
//            BuildConfig.VERSION_NAME,
//            Build.MODEL,
//            Build.VERSION.RELEASE
//        )

        val headersBuilder = Headers.Builder()
            .add("AUTH_TK", LoginManager.token ?: "")
            .add("AUTH_DID", AppUtils.getAndroidID())
            .add("platform", AppConstant.APP_CLIENT)
            .add("versionNum", "100")

        val headers = headersBuilder.build()

        request = chain.request().newBuilder()
            .headers(headers)
            .post(requestBody ?: emptyBody)
            .build()

        val response = chain.proceed(request)

        if (BuildConfig.DEBUG) {
            try {
                Timber.tag("发起请求")
                Timber.d(
                    """
                    ———————————————— 我是开始分割线 ——————————————————————————————
                    ${request.url} 
                    入参：
                    ${readBody(requestBody)}
                    响应：
                    ${clone(response.body)?.string()}
                    ———————————————— 我是结束分割线 ———————————————————————————————
                """.trimIndent()
                )
            } catch (e: Exception) {
                Timber.e("GlobalInterceptor request.exception : ${e.localizedMessage}}")
            }
        }

        return response
    }

    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())
    }
}