package com.gh.gamecenter.minigame

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.db.ISearchHistoryDao

/**
 * 微信小游戏-历史搜索记录
 */
class MiniGameSearchDao : ISearchHistoryDao {

    private val histories = MutableLiveData(all ?: emptyList())

    override fun add(keyword: String) {
        val originString = SPUtils.getString(SP_KEY)

        if (originString.isEmpty()) {
            // Insert keyword only for the very first time.
            SPUtils.setString(SP_KEY, keyword)
            histories.postValue(listOf(keyword))
        } else {
            all?.let {
                // Move keyword to the very front if it exists.
                if (it.contains(keyword)) {
                    it.remove(keyword)
                }
                it.add(0, keyword)
                val builder = StringBuilder()
                for ((index, key) in it.withIndex()) {
                    builder.append(key)
                    if (index != it.size - 1) {
                        builder.append(SEARCH_KEY_DIVIDER)
                    }
                }
                SPUtils.setString(SP_KEY, builder.toString())
                histories.postValue(it)
            }
        }
    }

    override fun getAll(): ArrayList<String>? {
        val list = SPUtils.getString(SP_KEY).split(SEARCH_KEY_DIVIDER)

        return if (list.size == 1 && list[0].isEmpty()) null else ArrayList(list)
    }

    override fun delete(item: String) {}

    override fun deleteAll() {
        SPUtils.setString(SP_KEY, "")
    }

    override fun getHistoryLiveData(): LiveData<List<String>> {
        return histories
    }

    companion object {
        const val SP_KEY = "mini_game_key"
        const val SEARCH_KEY_DIVIDER = "<-||->"
    }
}