package es.verdnatura.domain

import android.content.Context
import androidx.preference.PreferenceManager
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

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/api/"

        fun getApiService(context: Context): SalixService {
            val salixRetrofit = Retrofit.Builder().baseUrl(getBaseUrlLocal(context = context)).addConverterFactory(
                GsonConverterFactory.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 else url
        }

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