package com.rc.httpcore.interceptor

import android.annotation.SuppressLint
import android.content.Intent
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.rc.httpcore.HttpClient
import com.rc.httpcore.vo.CommonResponse
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.lang.Exception
import java.nio.charset.StandardCharsets

class TokenHeaderInterceptor : Interceptor {

    @SuppressLint("LongLogTag")
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest: Request = chain.request()
        val requestBuilder: Request.Builder = originalRequest.newBuilder()
        if (!HttpClient.token.isNullOrEmpty()) {
            requestBuilder.addHeader("authorization", HttpClient.token!!)
            Log.d("===========", HttpClient.token!!)
//            LogUtils.d("Token", HttpClient.token!!)
        }

        requestBuilder
//            .header("client", "android_app")
            .header("vName", HttpClient.vName)
            .header("Accept", "application/json, text/plain,*/*")
//            .header("Accept", "application/x-www-form-urlencoded")
            .build()

        val newlyRequest = requestBuilder.build()
//        if (newlyRequest.url().toString().contains("download")) {
//            return chain.proceed(newlyRequest);
//        }

        val response = chain.proceed(newlyRequest)
        try {
            response.body?.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()) {
                    HttpClient.getAppContext()?.apply {
                        val intent = Intent("com.rc.core.token_expired")
                        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return response
    }
}