package net.pokeranalytics.android.util

import android.content.Context
import android.preference.PreferenceManager
import java.util.*

class Preferences {

    enum class Keys(var identifier: String) {
        CURRENCY_CODE("CurrencyCode"),
        FIRST_LAUNCH("firstLaunch")
    }

    companion object {

        var currencyLocale : Locale? = null

        fun setString(key: Keys, value: String, context: Context) {
	        val preferences = PreferenceManager.getDefaultSharedPreferences(context)
	        val editor = preferences.edit()
	        editor.putString(key.identifier, value)
	        editor.apply()
        }

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

	    fun setBoolean(key: Keys, value: Boolean, context: Context) {
		    val preferences = PreferenceManager.getDefaultSharedPreferences(context)
		    val editor = preferences.edit()
		    editor.putBoolean(key.identifier, value)
		    editor.apply()
	    }

	    fun getBoolean(key: Keys, context: Context, defaultValue: Boolean? = false) : Boolean {
		    val preferences = PreferenceManager.getDefaultSharedPreferences(context)
		    return preferences.getBoolean(key.identifier, defaultValue ?: false)
	    }

        fun setCurrencyCode(currencyCode: String, context: Context) {
            Preferences.setString(Keys.CURRENCY_CODE, currencyCode, context)
            currencyLocale = null
        }

        private fun getCurrencyCode(context: Context) : String? {
            return Preferences.getString(Keys.CURRENCY_CODE, context)
        }

        fun getCurrencyLocale(context : Context) : Locale {

            currencyLocale?. let {
                return it
            }

            Preferences.getCurrencyCode(context)?.let { currencyCode ->
                Locale.getAvailableLocales().filter{
                    try {
                        Currency.getInstance(it).currencyCode == currencyCode
                    } catch (e: Exception) {
                        false
                    }
                }.first().let {
                    currencyLocale = it
                    return it
                }
            }
            currencyLocale = Locale.getDefault()
            return currencyLocale!!
        }
    }

}