package com.pixelized.biblib.network.client

import com.google.gson.Gson
import com.pixelized.biblib.network.client.IBibLibClient.Companion.BASE_URL
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Inject


class BibLibClient @Inject constructor(
    gson: Gson,
) : IBibLibClient {
    private val bearerInterceptor = BearerInterceptor()
    private val httpInterceptor = HttpLoggingInterceptor().apply {
        this.level = HttpLoggingInterceptor.Level.HEADERS
    }
    private val retrofit: Retrofit = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(gson))
        .client(
            OkHttpClient.Builder()
                .addInterceptor(bearerInterceptor)
                .addInterceptor(httpInterceptor)
                .callTimeout(1, TimeUnit.MINUTES)
                .connectTimeout(1, TimeUnit.MINUTES)
                .readTimeout(1, TimeUnit.MINUTES)
                .writeTimeout(1, TimeUnit.MINUTES)
                .build()
        )
        .baseUrl(BASE_URL)
        .build()

    override val service: IBibLibWebServiceAPI = retrofit.create(IBibLibWebServiceAPI::class.java)

    override var token: String?
        get() = bearerInterceptor.token
        set(value) {
            bearerInterceptor.token = value
        }
}