package com.isidroid.network

import com.google.gson.Gson
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.util.concurrent.TimeUnit

fun <T> createRetrofitApiClient(
    baseUrl: String,
    cl: Class<T>,
    logLevel: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.BODY,
    readTimeOut: Long = 15,
    writeTimeOut: Long = 60,
    gson: Gson,
    isDebugBuild: Boolean,
    interceptors: List<Interceptor?>? = null
): T = Retrofit.Builder()
    .client(
        httpClient(
            cl = cl,
            logLevel = logLevel,
            readTimeOut = readTimeOut,
            writeTimeOut = writeTimeOut,
            isDebugBuild = isDebugBuild,
            interceptors = interceptors
        )
    )
    .baseUrl(baseUrl)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build()
    .create(cl) as T


private fun <T> httpClient(
    cl: Class<T>,
    logLevel: HttpLoggingInterceptor.Level,
    readTimeOut: Long = 15,
    writeTimeOut: Long = 60,
    isDebugBuild: Boolean,
    interceptors: List<Interceptor?>?
): OkHttpClient {
    val builder = OkHttpClient().newBuilder()
        .readTimeout(readTimeOut, TimeUnit.SECONDS)
        .writeTimeout(writeTimeOut, TimeUnit.SECONDS)

    builder.addInterceptor(logger(cl = cl, logLevel = logLevel, isDebugBuild = isDebugBuild))

    interceptors?.filterNotNull()?.forEach { builder.addInterceptor(it) }

    return builder.build()
}

private fun <T> logger(cl: Class<T>, logLevel: HttpLoggingInterceptor.Level, isDebugBuild: Boolean) =
    HttpLoggingInterceptor { message -> Timber.tag(cl.simpleName).i(message) }
        .apply {
            level = logLevel

            if (!isDebugBuild)
                redactHeader("Authorization")
        }


val Boolean.sortDirection get() = if (this) "asc" else "desc"
