package com.tencent.liteav.demo.player.http

import android.content.Context
import android.os.Build
import com.tencent.liteav.demo.superplayer.util.HttpUtils
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

class AuthorizationInterceptor : Interceptor {
    private var token: String? = null

    override fun intercept(chain: Interceptor.Chain): Response {
        if (token == null) {
            val application = HttpUtils.getApplication()
            val sp =
                application.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE)

            token = sp.getString("flutter.token", null)
        }

        token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxMzY0ODM1MjU0MDY0ODgxNjY1IiwiZXhwIjoxNjYzODE3MDMxfQ.d_79J8e6yZnRpS8O6RXLfKPDWS6V4lkq1Q8NLekyMuE"

        val newRequest = chain.request()
            .newBuilder()
            .addHeader("token", token ?: "")
            .build()

        return try {
            chain.proceed(newRequest)
        } catch (e: Throwable) {
            Response.Builder().body(
                internalError(e.message ?: "网络错误").toResponseBody()
            ).build()
        }
    }

    private fun internalError(message: String): String {
        return "{\"status\":500,\"data\":null,\"msg\":\"${message}\"}".trimIndent()
    }
}