package ru.myitschool.work.api

import android.content.Context
import com.google.android.datatransport.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import ru.myitschool.work.api.list.ApiServiceList
import ru.myitschool.work.api.login.ApiServiceLogin
import ru.myitschool.work.api.main.ApiServiceMain
import ru.myitschool.work.api.scan.ApiServiceScan
import ru.myitschool.work.core.Constants.SERVER_ADDRESS
import ru.myitschool.work.utils.AuthPreferences
import java.util.concurrent.TimeUnit

class RetrofitClient(context: Context) {

    private val serverAddress = SERVER_ADDRESS
    private var authPreferences: AuthPreferences = AuthPreferences(context)


    private val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    private val httpClientWithAuth = OkHttpClient.Builder()
        .connectTimeout(5, TimeUnit.SECONDS)
        .addInterceptor(BasicAuthInterceptor(
            authPreferences.getLogin() ?: "",
            authPreferences.getPassword() ?: ""
        ))
        .addInterceptor(loggingInterceptor)
        .readTimeout(5, TimeUnit.SECONDS)
        .build()

    private val retrofitWithAuth: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(serverAddress)
            .client(httpClientWithAuth)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun getApiServiceLogin(): ApiServiceLogin {
        return retrofitWithAuth.create(ApiServiceLogin::class.java)
    }

    fun getApiServiceMain(): ApiServiceMain {
        return retrofitWithAuth.create(ApiServiceMain::class.java)
    }

    fun getApiServiceScanAuth(): ApiServiceScan {
        return retrofitWithAuth.create(ApiServiceScan::class.java)
    }

    fun getApiServiceList(): ApiServiceList {
        return retrofitWithAuth.create(ApiServiceList::class.java)
    }
}