package com.base.scanqr.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken


object SpJsonUtils {

    val TAG = "SpJsonUtils"

    inline fun <reified T> getSpJsonList(key: String): List<T> {
        val sp = AppPreferences.getInstance().getString(key, "")
        return if (sp.equals("")) {
            listOf()
        } else {
            val gson = Gson()
            val type = object : TypeToken<List<T>>() {}.type
            val list: List<T> = gson.fromJson(sp, type)
            return list
        }
    }

    fun <T> saveJsonBeanList(key: String, list: List<T>) {
        val json = Gson().toJson(list)
        AppPreferences.getInstance().put(key, json)
    }

    inline fun <reified T> addJsonBean(key: String, bean: T) {
        val arrayList = arrayListOf<T>()
        val list = getSpJsonList<T>(key)
        arrayList.addAll(list)
        arrayList.add(bean)
        saveJsonBeanList(key, arrayList.toList())
    }

    /**
     * 这里保存一定要找到具体的类型，不能用父类
     */
    inline fun <reified T> removeJsonBean(key: String, bean: T, crossinline removeIf: (it1: T, it2: T) -> Boolean) {
        val list = getSpJsonList<T>(key).toMutableList()
        list.removeIf { removeIf(it, bean) }
        saveJsonBeanList(key, list)
    }

}