package com.cheng.blzb.manager

import android.text.TextUtils
import com.example.base.utils.MMKVUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * 搜索历史
 */
object SearchHistoryManager {

    fun addHistory(keyword: String): List<String> {
        val list = getHistory()
        if (!list.contains(keyword)) {
            if (list.size == 20) list.removeLast()
            list.add(0, keyword)
            MMKVUtils.put("search_history", Gson().toJson(list))
        }
        return list
    }

    fun updateHistory(keyword: String): List<String> {
        val list = getHistory()
        if (list.contains(keyword)) {
            list.remove(keyword)
        }
        list.add(0, keyword)
        MMKVUtils.put("search_history", Gson().toJson(list))
        return list
    }

    fun getHistory(): MutableList<String> {
        val str = MMKVUtils.getString("search_history")
        if (!TextUtils.isEmpty(str)) {
            return Gson().fromJson(str, object : TypeToken<MutableList<String>>() {}.type)
        }
        return mutableListOf()
    }

    fun clear() {
        MMKVUtils.removeKey("search_history")
    }
}