package http.interceptor

import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.google.gson.Gson
import http.vo.CommonResponse
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import xn.xxp.room.RoomTool
import xn.xxp.utils.Tool
import java.lang.Exception
import java.nio.charset.StandardCharsets

class TokenHeaderInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest: Request = chain.request()
        val requestBuilder: Request.Builder = originalRequest.newBuilder()
        val config = RoomTool.getInstance().deviceConfigDao().deviceConfig
        val terminalAuth = config.terminalAuth
        if (!TextUtils.isEmpty(terminalAuth)) {
            requestBuilder.addHeader("TerminalAuth", terminalAuth)
        }
        requestBuilder
            .header("vName", "1.0.0")
            .header("Accept", "application/json, text/plain, */*")
            .build()
        val newlyRequest = requestBuilder.build()
        val url = newlyRequest.url.toString()
        val isPrint = url.contains("terminal/iot/monitor")
        if (!isPrint) {
            LogUtils.json(newlyRequest)
        }
        val response = chain.proceed(newlyRequest)
        val responseBody = response.body
        if (401 == response.code) {
            ThreadUtils.runOnUiThread {
                Toast.makeText(
                    ActivityUtils.getTopActivity(),
                    "鉴权失败,请重试!",
                    Toast.LENGTH_LONG
                )
                    .show()
                Tool.INSTANCE.reStartApp("鉴权失败")
            }
        }
        try {
            responseBody?.let {
                val source = it.source()
                source.request(Long.MAX_VALUE)
                val data = source.buffer.clone().readString(StandardCharsets.UTF_8)

                val commonResponse =
                    Gson().fromJson<CommonResponse>(data, CommonResponse::class.java)
                if (commonResponse.isTokenExpired()) {
                    ThreadUtils.runOnUiThread {
                        Toast.makeText(
                            ActivityUtils.getTopActivity(),
                            "鉴权失败,请重试!",
                            Toast.LENGTH_LONG
                        ).show()
                        Tool.INSTANCE.reStartApp("鉴权失败")
                    }
                }
            }
        } catch (e: Exception) {
            LogUtils.d(Log.getStackTraceString(e))
        }

        val responseBodyString = responseBody?.string() ?: ""
//        if (!AppUtils.isAppDebug()) {

        if (!isPrint) {
            if (response.code == 200) {
                LogUtils.d(response, responseBodyString)
            } else {
                LogUtils.e(response, responseBodyString)
            }
        }
//        }

        return response.newBuilder()
            .body(ResponseBody.create(responseBody?.contentType(), responseBodyString))
            .build()
    }
}