package com.sambath.kunkhmer.util


import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.sambath.kunkhmer.remote.LottoSet


/**
 * Singleton class for managing preferences for POJO or model class's object.

 */
object ModelPreferencesManager {

    //Shared Preference field used to save and retrieve JSON string
    lateinit var preferences: SharedPreferences

    //Name of Shared Preference file
    private const val PREFERENCES_FILE_NAME = "PREFERENCES_MODEL_FILE"

    /**
     * Call this first before retrieving or saving object.
     *
     * @param application Instance of application class
     */
    fun with(application: Application) {
        preferences = application.getSharedPreferences(
            PREFERENCES_FILE_NAME, Context.MODE_PRIVATE)
    }

    /**
     * Saves object into the Preferences.
     *
     * @param `object` Object of model class (of type [T]) to save
     * @param key Key with which Shared preferences to
     **/
    fun <T> put(`object`: T, key: String) {
        //Convert object to JSON String.
        val jsonString = GsonBuilder().create().toJson(`object`)
        //Save that String in SharedPreferences
        preferences.edit().putString(key, jsonString).apply()
    }
    fun putList(list: List<LottoSet>, key: String) {
        val jsonString = GsonBuilder().create().toJson(list)

        preferences.edit().putString(key, jsonString).apply()
    }
    /**
     * Used to retrieve object from the Preferences.
     *
     * @param key Shared Preference key with which object was saved.
     **/
     fun  getList(key: String): List<LottoSet>? {
        val value = preferences.getString(key, null)
        val type = object : TypeToken<List<LottoSet>>() {}.type
        return GsonBuilder().create().fromJson<List<LottoSet>>(value, type)

    }

    inline fun <reified T> get(key: String): T? {
        //We read JSON String which was saved.
        val value = preferences.getString(key, null)
        //JSON String was found which means object can be read.
        //We convert this JSON String to model object. Parameter "c" (of
        //type Class < T >" is used to cast.
        return GsonBuilder().create().fromJson(value, T::class.java)
    }
//    fun saveLottoToSharedPrefs(lottoSetList: List<LottoSet>) {
//        //val gson = Gson()
//        val json = GsonBuilder().create().toJson(lottoSetList)
//        preferences.edit().putString(Const.LOTTO_KEY, json).apply()
//    }
//    fun getLottoFromSharedPrefs(): List<*>? {
//        val json = preferences.getString(Const.LOTTO_KEY, null)
//        val tasks = GsonBuilder().create().fromJson<Any>(json, object : TypeToken<ArrayList<LottoSet>?>() {}.type)
//        return tasks as List<*>?
//    }
}