package com.f3401pal.csm.api

import com.f3401pal.csm.BuildConfig
import com.f3401pal.csm.Config
import com.squareup.moshi.Moshi
import dagger.Module
import dagger.Provides
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.CallAdapter
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Singleton

@Module
class ApiModule {

    private val HTTP_LOG_LEVEL = HttpLoggingInterceptor.Level.HEADERS

    @Singleton
    @Provides
    fun provideOpenDataApi(retrofit: Retrofit): CbeOverlayApi {
        return retrofit.create(CbeOverlayApi::class.java)
    }

    @Singleton
    @Provides
    fun provideRetrofit(okHttp: OkHttpClient, converter: Converter.Factory,
                        callAdapter: CallAdapter.Factory): Retrofit {
        val builder = Retrofit.Builder()
        builder.baseUrl(Config.BASE_URL_CBE)
                .client(okHttp)
                .addConverterFactory(converter)
                .addCallAdapterFactory(callAdapter)
        return builder.build()
    }

    @Singleton
    @Provides
    fun provideOkHttp(): OkHttpClient {
        val builder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) {
            val logging = HttpLoggingInterceptor()
            logging.level = HTTP_LOG_LEVEL
            builder.addInterceptor(logging)
        }
        return builder.build()
    }

    @Singleton
    @Provides
    fun provideMoshiConverterFactory(): Converter.Factory {
        val builder = Moshi.Builder()
        return MoshiConverterFactory.create(builder.build())
    }

    @Singleton
    @Provides
    fun provideCallAdapterFactory(): CallAdapter.Factory {
        return RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())
    }
}