package com.gh.gamecenter.amway.search

import com.gh.gamecenter.core.utils.SPUtils

class AmwaySearchDao {
    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)
        } else {
            getAll()?.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())
            }
        }
    }

    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)
    }

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

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