package com.develop.food.base.http


import android.util.Log
import com.develop.base.BuildConfig
import com.develop.food.base.http.adapter.GsonConverterFactory
import com.develop.food.base.http.adapter.LiveDataCallAdapterFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

class HttpFactory(url: String, userInterceptor: Interceptor = BaseInterceptor()) {
    var baseUrl: String = url
    var interceptor: Interceptor = userInterceptor
    var okHttpClient: OkHttpClient = createDefaultHttpClient()
    var retrofit: Retrofit = createDefaultRetrofit()

    private fun createDefaultHttpClient(): OkHttpClient {
        val logger = HttpLoggingInterceptor {
            if (BuildConfig.DEBUG) {
                Log.d("ApiResponse", it)
            }
        }
        logger.level = HttpLoggingInterceptor.Level.BODY
        return OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(interceptor)
            .addInterceptor(logger)
            .build()
    }

    private fun createDefaultRetrofit(): Retrofit {
        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(LiveDataCallAdapterFactory())
            .build()
    }

}