package com.gamedog.vididin.netbase

import com.gamedog.vididin.VidiConst
import com.gamedog.vididin.core.network.di.GlobalInterceptor
import com.gamedog.vididin.core.network.di.GlobalInterceptor2
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitUtil {

    private var retrofit: Retrofit? = null
    private const val DEFAULT_BASE_URL = VidiConst.URL_ZERO_BUY


    fun getRetrofitInstance(baseUrl: String = DEFAULT_BASE_URL, headers: Map<String, String> = emptyMap()): Retrofit {
        return retrofit ?: createRetrofit(baseUrl, headers).also { retrofit = it }
    }

    private fun createRetrofit(baseUrl: String, headers: Map<String, String>): Retrofit {
        val okHttpClient = OkHttpClient.Builder().apply {
            // add request custom head
            if (headers.isNotEmpty()) {
                addInterceptor { chain ->
                    val originalRequest = chain.request()
                    val requestBuilder = originalRequest.newBuilder()
                    headers.forEach { (key, value) ->
                        requestBuilder.addHeader(key, value)
                    }
                    chain.proceed(requestBuilder.build())
                }
            }

            // TODO - only enable in debug mode
            addInterceptor(GlobalInterceptor2())
            connectTimeout(30, TimeUnit.SECONDS)
            readTimeout(30, TimeUnit.SECONDS)
            writeTimeout(30, TimeUnit.SECONDS)
        }.build()

        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}