package es.verdnatura.domain

import android.content.Context
import es.verdnatura.MobileApplication
import es.verdnatura.domain.ConstAndValues.BASEURL
import es.verdnatura.domain.ConstAndValues.BASE_URL
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 ApiUtils {
    companion object {

        fun getApiService(context: Context, myObserver: InteceptorListener?): VerdnaturaService {
            var client = OkHttpClient.Builder().addInterceptor(SilexInterceptor(context,myObserver))
                .connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(40, TimeUnit.SECONDS).build()

            val retrofit = Retrofit.Builder().baseUrl(getBaseUrlLocal(context))
                .addConverterFactory(GsonConverterFactory.create()).client(client).build()

            return retrofit.create(VerdnaturaService::class.java)
        }

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

    }

}