package com.swoosh.microblog.data.api

import com.swoosh.microblog.data.UrlNormalizer
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object ApiClient {

    @Volatile
    private var retrofit: Retrofit? = null

    @Volatile
    private var currentBaseUrl: String? = null

    fun getService(baseUrl: String, apiKeyProvider: () -> String?): GhostApiService {
        val normalizedUrl = UrlNormalizer.normalize(baseUrl)

        if (retrofit == null || currentBaseUrl != normalizedUrl) {
            synchronized(this) {
                if (retrofit == null || currentBaseUrl != normalizedUrl) {
                    val logging = HttpLoggingInterceptor().apply {
                        level = HttpLoggingInterceptor.Level.BODY
                    }

                    val client = OkHttpClient.Builder()
                        .addInterceptor(GhostAuthInterceptor(apiKeyProvider))
                        .addInterceptor(logging)
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build()

                    retrofit = Retrofit.Builder()
                        .baseUrl(normalizedUrl)
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()

                    currentBaseUrl = normalizedUrl
                }
            }
        }

        return retrofit!!.create(GhostApiService::class.java)
    }

    fun reset() {
        synchronized(this) {
            retrofit = null
            currentBaseUrl = null
        }
    }

}
