package com.guadou.lib_baselib.base

import com.guadou.lib_baselib.utils.interceptor.*
import com.hjq.gson.factory.GsonFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 * 基类的Retrofit对象
 */
abstract class BaseRetrofitClient {

    companion object {
        //静态常量
        private const val TIME_OUT = 20
    }

    private val client: OkHttpClient
        get() {
            val builder = OkHttpClient.Builder()

            //可以添加日志拦截和参数拦截
            builder
                .addInterceptor(LoggingInterceptor())
//                .addInterceptor(HeadInterceptor())
                .connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
                .readTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)

//            if (needHttpCache()) {
//                handleBuilder(builder)
//            }

            return builder.build()
        }

//    open protected fun needHttpCache(): Boolean = false

//    /**
//     * 处理缓存
//     */
//    private fun handleBuilder(builder: OkHttpClient.Builder) {
//
//        val httpCacheDirectory = File(CommUtils.getContext().cacheDir, "responses") //Http缓存目录
//        val cacheSize = 10 * 1024 * 1024L // 10 MiB
//        val cache = Cache(httpCacheDirectory, cacheSize)     //Http缓存对象
//        builder.cache(cache)
//            .cookieJar(cookieJar)
//            .addInterceptor { chain ->
//                var request = chain.request()
//
//                if (!NetWorkUtil.isAvailable(CommUtils.getContext())) {
//                    request = request.newBuilder()
//                        .cacheControl(CacheControl.FORCE_CACHE)
//                        .build()
//                }
//
//                val response = chain.proceed(request)
//                //有网络读取接口，没有网络展示缓存
//                if (!NetWorkUtil.isAvailable(CommUtils.getContext())) {
//                    val maxAge = 60 * 60
//                    response.newBuilder()
//                        .removeHeader("Pragma")
//                        .header("Cache-Control", "public, max-age=$maxAge")
//                        .build()
//                } else {
//                    val maxStale = 60 * 60 * 24 * 28 // tolerate 4-weeks stale
//                    response.newBuilder()
//                        .removeHeader("Pragma")
//                        .header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
//                        .build()
//                }
//                response
//            }
//    }

    fun <S> getService(serviceClass: Class<S>, baseUrl: String): S {
        return Retrofit.Builder()
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(GsonFactory.getSingletonGson()))  //使用框架进行容错
            .baseUrl(baseUrl)
            .build()
            .create(serviceClass)
    }

}
