package com.base.browserwhite.utils

import com.base.browserwhite.bean.SpBean
import com.google.gson.Gson

object SpBeanUtils {


    const val BOOKMARK_SP_KEY = "bookmark_sp_key"//书签
    const val BOOKMARK_NAV_SP_KEY = "bookmark_nav_sp_key"//书签导航
    const val HISTORY_SP_KEY = "history_sp_key"//历史记录
    const val SEARCH_RECORD_SP_KEY = "search_record_sp_key"//搜索记录

    fun getSpBeanList(key: String): List<String> {
        val sp = AppPreferences.getInstance().getString(key, "")
        return if (sp.equals("")) {
            listOf()
        } else {
            sp.split("|||")
        }
    }

    fun deleteSpBeanCondition(key: String, id: Long) {

        val list = getSpBeanList(key).toMutableList()
        val deleteItem = list.find { Gson().fromJson(it, SpBean::class.java).id == id }
        list.remove(deleteItem)

        val string = list.joinToString(separator = "|||")

        AppPreferences.getInstance().put(key, string)
    }


    fun addSpBean(key: String, bean: SpBean): Long {
        val list = getSpBeanList(key).toMutableList()
        bean.id = if (list.isNotEmpty()) {
            val lastSpBean: SpBean? = Gson().fromJson(list.last(), SpBean::class.java)
            (lastSpBean?.id ?: 0) + 1
        } else {
            1
        }
        val value = Gson().toJson(bean)
        list.add(value)
        val string = list.joinToString(separator = "|||")
        AppPreferences.getInstance().put(key, string)
        return bean.id
    }


    fun clearSpBean(key: String) {
        AppPreferences.getInstance().put(key, "")
    }

    fun editSpBean(key: String, bean: SpBean) {
        val gson = Gson()
        val list = getSpBeanList(key).toMutableList()
        val oldItem = list.find { gson.fromJson(it, SpBean::class.java).id == bean.id }
        val index = list.indexOf(oldItem)
        list.remove(oldItem)
        list.add(index, gson.toJson(bean))

        val string = list.joinToString(separator = "|||")
        AppPreferences.getInstance().put(key, string)
    }

}