package com.img.rabbit.provider.utils

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import com.img.rabbit.BuildConfig
import com.img.rabbit.config.Constants
import com.img.rabbit.utils.AESpkcs7paddingUtil
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException


/**
 * 解密数据
 */
class ResponseInterceptor : Interceptor {
    private val TAG = "Decode"
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val url = request.url
        val apiPath = String.format("%s", url)
        val baseUrl = if (BuildConfig.DEBUG) {
            Constants.DEBUG_BASE_URL
        } else {
            Constants.RELEASE_BASE_URL
        }
        //如果请求的不是服务端的接口则不用加密
        if (!apiPath.startsWith(baseUrl)) {
            return chain.proceed(request)
        }
        val response = chain.proceed(request)
        var charset = Charset.forName("UTF-8")
        val contentType = response.header("Content-Type")
        if (contentType != null && contentType.contains("application/json")) {
            val responseBody = response.body
            val source = responseBody.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer
            val mediaType = responseBody.contentType()
            if (mediaType != null) {
                try {
                    charset = mediaType.charset(Charset.forName("UTF-8"))
                } catch (e: UnsupportedCharsetException) {
                    e.printStackTrace()
                }
            }
            val respBody = buffer.clone().readString(charset!!)
            Log.w(TAG, "response=${respBody}")
            if (TextUtils.isEmpty(respBody)) {
                val responseCode = if (response.code == 400) 200 else response.code //兼容某些接口400的情况
                return response.newBuilder().code(responseCode).body(responseBody).build()
            }

            val isEncrypt = JSONObject(respBody).optBoolean("encrypt")
            Log.w(TAG, "是否需要解密:$isEncrypt")
            if (!isEncrypt) { //如果不需要加密 直接返回
                Log.w(TAG, "response=${response.body}")
                val responseCode = if (response.code == 400) 200 else response.code //兼容某些接口400的情况
                return response.newBuilder().code(responseCode).body(responseBody).build()
            }
            val decrybody = JSONObject(respBody).optString("data")
            Log.w(TAG, "Json解析后的字符串为---->$decrybody")
            var decryString: String?
            try {
                decryString = AESpkcs7paddingUtil.decryptNormal(decrybody, Constants.AESDecrypt)
                Log.e("ResponseInterceptor", "解密后返回的字符串为---->$decryString")

                //这里可以通过code处理token过去过期的情况
                //val decCode = JSONObject(decryString).optInt("code")

                //返回新创建的response
                val responseCode = if (response.code == 400 && decrybody != null) 200 else response.code //兼容某些接口400的情况
                return response.newBuilder().code(responseCode).body(decryString.toResponseBody("text/plain".toMediaType())).build()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return response
    }

}