package es.verdnatura.domain

import android.content.Context
import android.content.SharedPreferences
//import android.preference.PreferenceManager
import androidx.preference.PreferenceManager
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class ApiUtils {
    companion object {
        //const val BASE_URL:String = "http://192.168.1.54:8009/"
        //const val BASE_URL:String = "https://10.1.2.79/"

        const val BASE_URL: String = "https://app.verdnatura.es/"


        fun getApiService(context: Context): VerdnaturaService {

            val retrofit = Retrofit.Builder()
                .baseUrl(getBaseUrlLocal(context))
                .addConverterFactory(GsonConverterFactory.create())
                .client(getRequestHeader()!!)
                .build()
            return retrofit.create(VerdnaturaService::class.java)

        }

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

        fun getRequestHeader(): OkHttpClient? {
            return OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(40, TimeUnit.SECONDS)
                .build()
        }

        fun setDefaults(key: String?, value: String?, context: Context?) {
            val preferences: SharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(context)
            val editor = preferences.edit()
            editor.putString(key, value)
            //editor.commit()
            editor.apply()
        }

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

    }

}