package xn.hxp.utils

import android.content.Context
import android.content.SharedPreferences
import xn.hxp.ui.DoubleDialogBean
import xn.hxp.ui.SettingsBean
import com.google.gson.Gson

/**
 * @author 前同事代码
 */
object SharedPreferencesHelper {
    private const val PREF_NAME = "MyPreferences"
    private const val KEY_MY_LIST = "myList"
    private const val URL_BASE_NAME = "urlBaseName"
    private const val URL_BASE_VLE = "urlBaseVle"


    fun saveUrlBase(context: Context, bean: SettingsBean) {
        val sharedPreferences: SharedPreferences =
            context.getSharedPreferences(URL_BASE_NAME, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        val gson = Gson()
        val json = gson.toJson(bean)
        editor.putString(URL_BASE_VLE, json)
        editor.apply()
    }

    fun getUrlBase(context: Context): SettingsBean? {
        val sharedPreferences: SharedPreferences =
            context.getSharedPreferences(URL_BASE_NAME, Context.MODE_PRIVATE)
        val gson = Gson()
        val json = sharedPreferences.getString(URL_BASE_VLE, "")
        return if (json != null) {
            gson.fromJson(json, SettingsBean::class.java)
        } else {
            null
        }
    }


    fun saveList(context: Context, list: List<DoubleDialogBean>) {
        val sharedPreferences: SharedPreferences =
            context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        val gson = Gson()
        val json = gson.toJson(list)
        editor.putString(KEY_MY_LIST, json)
        editor.apply()
    }

    fun getList(context: Context): List<DoubleDialogBean> {
        val sharedPreferences: SharedPreferences =
            context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        val gson = Gson()
        val json = sharedPreferences.getString(KEY_MY_LIST, "")
        return if (json.isNullOrEmpty()) {
            emptyList()
        } else {
            gson.fromJson(json, Array<DoubleDialogBean>::class.java).toList()
        }
    }

    fun clearList(context: Context) {
        val sharedPreferences: SharedPreferences =
            context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.remove(KEY_MY_LIST)
        editor.apply()
    }

    fun clearBeans(context: Context) {
        val sharedPreferences: SharedPreferences =
            context.getSharedPreferences(URL_BASE_NAME, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.remove(URL_BASE_VLE)
        editor.apply()
    }


}