package es.verdnatura.domain

import android.content.Context
import com.google.gson.GsonBuilder
import es.verdnatura.MobileApplication
import es.verdnatura.domain.ConstAndValues.BASEURLSALIX
import es.verdnatura.domain.ConstAndValues.BASE_URL_SALIX
import es.verdnatura.presentation.common.InteceptorListener
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class ApiSalixUtils {
    companion object {

        fun getApiService(context: Context, myObserver: InteceptorListener?): SalixService {

            var salixClient =
                OkHttpClient.Builder().addInterceptor(SalixInterceptor(context, myObserver))
                    .connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(40, TimeUnit.SECONDS).build()

            val salixRetrofit =
                Retrofit.Builder().client(salixClient).baseUrl(getBaseUrlLocal(context = context))
                    .addConverterFactory(
                        GsonConverterFactory.create(GsonBuilder().serializeNulls().create())
                    ).build()

            return salixRetrofit.create(SalixService::class.java)
        }

        private fun getBaseUrlLocal(context: Context): String {
            var url =
                (context as MobileApplication).dataStoreApp.readDataStoreKey<String>(BASEURLSALIX)
            if (url.isNullOrEmpty()) {
                runBlocking {
                    (context).dataStoreApp.editDataStoreKey(
                        BASEURLSALIX, BASE_URL_SALIX
                    )
                }
            } else {
                if (!url.contains("http")) {
                    url = "https://" + url
                }
            }
            return if (url.isNullOrEmpty()) "$BASE_URL_SALIX/api/" else "$url/api/"
        }
    }
}