package com.bc_chat.bc_base.http

import android.text.TextUtils
import com.bc_chat.bc_base.BuildConfig
import com.bc_chat.bc_base.utils.AppConfig
import com.zhaohaoting.framework.requset.rxjava_retrofit.BaseRetrofitHelper
import com.zhaohaoting.framework.utils.Logger
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
import java.util.concurrent.TimeUnit

/**
 * author：Created by zhaohaoting on 2018/1/10 11:51
 * email：526309416@qq.com
 * desc：
 */

class RetrofitHelper private constructor() : BaseRetrofitHelper<Api>() {
    companion object {
        val api: Api by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            RetrofitHelper().getApiService(Api::class.java, BuildConfig.BaseUrl)
        }
    }

    override fun getInterceptor(): Interceptor {
        return LoggingInterceptor()
    }

    inner class LoggingInterceptor : Interceptor {
        private val UTF8 = Charset.forName("UTF-8")

        override fun intercept(chain: Interceptor.Chain): Response {
            val originalRequest = chain.request()
            val requestBody = originalRequest.body()
            var body: String? = null
            val builder = originalRequest.newBuilder()
            val userId = AppConfig.instance.getUser().userId
            builder.addHeader("uid", if (TextUtils.isEmpty(userId)) "0" else userId)
            if (requestBody != null) {
                val buffer = Buffer()
                requestBody.writeTo(buffer)

                var charset: Charset? = UTF8
                val contentType = requestBody.contentType()
                if (contentType != null) {
                    charset = contentType.charset(UTF8)
                }
                body = buffer.readString(charset!!)
            }

            val requestBuilder = builder.method(originalRequest.method(), requestBody)
            val startNs = System.nanoTime()
            val request = requestBuilder.build()
            val response = chain.proceed(request)

            val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)

            val responseBody = response.body()
            var rBody: String? = null

            if (responseBody != null) {
                val source = responseBody.source()
                source.request(java.lang.Long.MAX_VALUE) // Buffer the entire body.
                val buffer = source.buffer()

                var charset: Charset? = UTF8
                val contentType = responseBody.contentType()
                if (contentType != null) {
                    try {
                        charset = contentType.charset(UTF8)
                    } catch (e: UnsupportedCharsetException) {
                        e.printStackTrace()
                    }

                }
                rBody = buffer.clone().readString(charset!!)
            }
            Logger.e("request", request.method() + "  " + request.url() + "  " + request.headers() + "\n" + body)
            Logger.e("response", response.code().toString() + rBody!!)

            return response
        }
    }
}
