package com.gh.gamecenter.common.base

import android.content.Context
import android.content.SharedPreferences
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.core.utils.SPUtils

/**
 * 用 SP 实现的简单列表持久化结构
 */
abstract class BaseSimpleDao {

    // 使用独有的 SP 文件
    private val mSp: SharedPreferences by lazy {
        HaloApp.getInstance().getSharedPreferences("SimpleDao", Context.MODE_PRIVATE)
    }

    fun add(key: String) {
        val originString = SPUtils.getString(mSp, getSPKey())

        if (originString.isEmpty()) {
            // Insert keyword only for the very first time.
            SPUtils.setString(mSp, getSPKey(), key)
        } else {
            getAll()?.let {
                if (getMaxSize() != -1 && it.size > getMaxSize()) {
                    it.removeAt(it.size - 1)
                }

                // Move keyword to the very front if it exists.
                if (it.contains(key)) {
                    it.remove(key)
                }
                it.add(0, key)
                val builder = StringBuilder()
                for ((index, k) in it.withIndex()) {
                    builder.append(k)
                    if (index != it.size - 1) {
                        builder.append(DIVIDER_KEY)
                    }
                }
                SPUtils.setString(mSp, getSPKey(), builder.toString())
            }
        }
    }

    fun delete(key: String) {
        val originString = SPUtils.getString(mSp, getSPKey())

        if (originString.isEmpty()) {
            // do nothing
        } else {
            getAll()?.let {
                if (it.contains(key)) {
                    it.remove(key)
                }
                val builder = StringBuilder()
                for ((index, k) in it.withIndex()) {
                    builder.append(k)
                    if (index != it.size - 1) {
                        builder.append(DIVIDER_KEY)
                    }
                }
                SPUtils.setString(mSp, getSPKey(), builder.toString())
            }
        }
    }

    fun getAll(): ArrayList<String>? {
        val list = SPUtils.getString(mSp, getSPKey()).split(DIVIDER_KEY)

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

    fun getRawString(): String = SPUtils.getString(mSp, getSPKey())

    fun contains(key: String): Boolean {
        return getAll()?.contains(key) == true
    }

    fun deleteAll() {
        SPUtils.setString(mSp, getSPKey(), "")
    }

    open fun getMaxSize(): Int = -1

    abstract fun getSPKey(): String

    companion object {
        private const val DIVIDER_KEY = "<-||->"
    }

}