package de.sebse.fuplanner2.preferences

import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences

class AppPreferences(val context: Context) {
    private val preferences: SharedPreferences = context.getSharedPreferences(APP_PREFERENCES_SCREEN, MODE_PRIVATE)

    fun remove(key: String) = preferences.edit().remove(key).apply()

    fun getString(key: String): String? = preferences.getString(key, null)
    fun set(key: String, value: String) = preferences.edit().putString(key, value).apply()

    fun getBoolean(key: String): Boolean? = if (preferences.contains(key)) preferences.getBoolean(key, false) else null
    fun set(key: String, value: Boolean) = preferences.edit().putBoolean(key, value).apply()

    fun getInt(key: String): Int? = if (preferences.contains(key)) preferences.getInt(key, 0) else null
    fun set(key: String, value: Int) = preferences.edit().putInt(key, value).apply()

    fun getLong(key: String): Long? = if (preferences.contains(key)) preferences.getLong(key, 0) else null
    fun set(key: String, value: Long) = preferences.edit().putLong(key, value).apply()

    companion object {
        const val APP_PREFERENCES_SCREEN = "app"

        private var sInstance: AppPreferences? = null

        fun initialize(context: Context): AppPreferences? {
            if (sInstance == null) {
                synchronized(AppPreferences::class.java) {
                    if (sInstance == null) {
                        sInstance = AppPreferences(context.applicationContext)
                    }
                }
            }
            return sInstance
        }

        fun getInstance(): AppPreferences {
            sInstance?.let {
                return it
            }
            throw NullPointerException("Please call initialize() before getting the instance.")
        }
    }
}