package net.pokeranalytics.android.api

import android.content.Context
import net.pokeranalytics.android.BuildConfig
import net.pokeranalytics.android.R
import net.pokeranalytics.android.model.retrofit.CurrencyConverterValue
import net.pokeranalytics.android.util.URL
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import java.util.concurrent.TimeUnit

/**
 * CurrencyCode Converter API
 */
interface CurrencyConverterApi {

	companion object {

		private var currencyConverterApi: CurrencyConverterApi? = null

		fun getApi(context: Context): CurrencyConverterApi? {

			if (currencyConverterApi == null) {

				var serviceEndpoint = URL.API_CURRENCY_CONVERTER

				val httpClient = OkHttpClient.Builder()

				// Logging interceptor
				if (BuildConfig.DEBUG) {
					val interceptor = HttpLoggingInterceptor()
					interceptor.level = HttpLoggingInterceptor.Level.BASIC
					httpClient.addInterceptor(interceptor)
				}

				// Add headers
				val interceptor = Interceptor { chain ->
					val original = chain.request()
					val originalHttpUrl = original.url()

					val url = originalHttpUrl.newBuilder()
						.addQueryParameter("apiKey", context.getString(R.string.currency_converter_api))
						.build()

					val requestBuilder = original.newBuilder()
						.url(url)

					chain.proceed(requestBuilder.build())
				}
				httpClient.addInterceptor(interceptor)

				val client = httpClient
					.readTimeout(60, TimeUnit.SECONDS)
					.connectTimeout(60, TimeUnit.SECONDS)
					.build()

				val retrofit = Retrofit.Builder()
					.addConverterFactory(GsonConverterFactory.create())
					.baseUrl(serviceEndpoint.value)
					.client(client)
					.build()

				currencyConverterApi = retrofit.create(CurrencyConverterApi::class.java)
			}

			return currencyConverterApi
		}

	}

	@GET("convert")
	fun convert(@Query("q") currencies: String, @Query("compact") compact: String = "y"): Call<Map<String, CurrencyConverterValue>>

}
