package com.remax.visualnovel.api.factory

import androidx.core.net.toUri
import com.remax.visualnovel.BuildConfig
import com.remax.visualnovel.api.interceptor.GlobalInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ServiceFactory {
    /**
     * 受信任的host列表
     */
    private val hostNameList: List<String?> by lazy {
        listOf(
            BuildConfig.API_FROG,
            BuildConfig.HOST
        ).map {
            it.parseHost()
        }
    }

    private fun String.parseHost() = this.toUri().host

    private val retrofit: Retrofit by lazy {
        createRetrofit()
    }

    private val okHttpClient: OkHttpClient by lazy {
        createOkHttpClient()
    }

    /**
     * 构建OkHttpClient对象
     */
    private fun createOkHttpClient() = OkHttpClient.Builder()
        .addInterceptor(GlobalInterceptor())
        .callTimeout(30, TimeUnit.SECONDS)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .hostnameVerifier { hostname, _ ->
            hostname in hostNameList
        }
        .apply {
            if (BuildConfig.DEBUG) {
                val interceptor = HttpLoggingInterceptor()
                interceptor.level = HttpLoggingInterceptor.Level.BODY
                addNetworkInterceptor(interceptor)
            }
        }.build()

    /**
     * 构建Retrofit对象
     */
    private fun createRetrofit() = Retrofit.Builder()
        .baseUrl(BuildConfig.API_FROG)
        .client(okHttpClient)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    inline fun <reified T> createService(): T = create(T::class.java)

    fun <T> create(clazz: Class<T>): T {
        return retrofit.create(clazz)
    }

}
