package com.doverfuelingsolutions.issp.api.basic

import com.doverfuelingsolutions.issp.api.WayneApiConfig
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.time.Duration
import java.util.concurrent.TimeUnit

object RetrofitUtil {

    private val loggingInterceptor = LoggingInterceptor()
    private val authInterceptor = AuthInterceptor()
    private val connectionPool =  ConnectionPool(50,5,TimeUnit.MINUTES);

    private val basicHttpBuilder = OkHttpClient.Builder()
        .connectTimeout(WayneApiConfig.timeoutConnect, TimeUnit.SECONDS)
        .readTimeout(WayneApiConfig.timeoutAll, TimeUnit.SECONDS)
        .writeTimeout(WayneApiConfig.timeoutAll, TimeUnit.SECONDS)
        .callTimeout(WayneApiConfig.timeoutAll, TimeUnit.SECONDS) // timeout for complete call
        .connectionPool(connectionPool)
        .addInterceptor(loggingInterceptor)
    private val authHttpBuilder = OkHttpClient.Builder()
        .connectTimeout(WayneApiConfig.timeoutConnect, TimeUnit.SECONDS)
        .readTimeout(WayneApiConfig.timeoutAll, TimeUnit.SECONDS)
        .writeTimeout(WayneApiConfig.timeoutAll, TimeUnit.SECONDS)
        .callTimeout(WayneApiConfig.timeoutAll, TimeUnit.SECONDS)
        .connectionPool(connectionPool)
        .addInterceptor(authInterceptor)
        .addInterceptor(loggingInterceptor)
    private val payHttpBuilder = OkHttpClient.Builder()
        .connectTimeout(WayneApiConfig.timeoutConnect, TimeUnit.SECONDS)
        .readTimeout(WayneApiConfig.timeoutPayRead, TimeUnit.SECONDS)
        .writeTimeout(WayneApiConfig.timeoutPayWrite, TimeUnit.SECONDS)
        .callTimeout(WayneApiConfig.timeoutPayCall, TimeUnit.SECONDS)
        .connectionPool(connectionPool)
        .addInterceptor(authInterceptor)
        .addInterceptor(loggingInterceptor)

    private val mGsonConverterFactory: GsonConverterFactory by lazy { GsonConverterFactory.create() }

    fun getGsonBuilder(): Retrofit.Builder {
        return Retrofit.Builder()
            .addConverterFactory(mGsonConverterFactory)
            .client(basicHttpBuilder.build())
    }

    fun getAuthBuilder(): Retrofit.Builder {
        return Retrofit.Builder()
            .addConverterFactory(mGsonConverterFactory)
            .client(authHttpBuilder.build())
    }

    fun getPayBuilder():Retrofit.Builder {
        return Retrofit.Builder()
            .addConverterFactory(mGsonConverterFactory)
            .client(payHttpBuilder.build())
    }
}