package es.verdnatura.domain

import android.content.Context
import androidx.preference.PreferenceManager
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class ApiSalixUtils {
    companion object {
        //const val BASE_URL:String = "http://192.168.1.155:9009/"
         //const val BASE_URL: String = "https://test-salix.verdnatura.es/api/"
         const val BASE_URL: String = "https://salix.verdnatura.es"

        fun getApiService(context: Context): SalixService {

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

           /* val salixRetrofit = Retrofit.Builder()
                .baseUrl(ApiUtils.getBaseUrlLocal(context))
                .addConverterFactory(GsonConverterFactory.create())
                .client(salixClient)
                .build()

            return salixRetrofit.create(SalixService::class.java)*/


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

            //d("VERDNATURA::","El server Salix es "+getBaseUrlLocal(context = context))
            return salixRetrofit.create(SalixService::class.java)
        }

        fun getBaseUrlLocal(context: Context): String {
            var url = this.getDefaults("base_urlSalix", context)
            if (url.isNullOrEmpty()) {
                ApiUtils.setDefaults("base_urlSalix", BASE_URL, context)
            } else {
                if (!url.contains("http")) {
                    url = "https://" + url
                }
            }
            return if (url.isNullOrEmpty()) "$BASE_URL/api/" else "$url/api/"
        }

        fun getDefaults(key: String?, context: Context?): String? {
            val preferences = PreferenceManager.getDefaultSharedPreferences(context)
            return preferences.getString(key, null)
        }
    }
}