package com.mogo.cloud.network.interceptor

import android.util.Log
import com.elegant.network.utils.GsonUtil
import com.mogo.cloud.network.BaseData
import com.mogo.cloud.passport.MoGoAiCloudClient
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Response
import okhttp3.ResponseBody

/**
 * created by donghongyu on 2021/1/28 14:33
 * describe: 令牌拦截，如果发现令牌过期需要重新获取令牌
 */
class HttpPassportInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        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()
            val response: BaseData<*>? = GsonUtil.objectFromJson(responseContent, BaseData::class.java)
            // 处理Token异常
            if (response?.code == 100046 ||
                response?.code == 100045 ||
                response?.code == 100005 ||
                response?.code == 100006 ||
                response?.code == 520003
            ) {
                Log.e("HttpPassportInterceptor", "Token 异常：$response")
                MoGoAiCloudClient.getInstance().refreshToken()
            }
            consumedResponse = true
        }
        return if (consumedResponse) response.newBuilder()
            .body(ResponseBody.create(contentType, responseContent)).build() else response

    }
}