package com.gh.gamecenter.forum.home

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

class ForumRecordDao {
    fun add(id: String) {
        val originString = SPUtils.getString(SP_KEY)

        if (originString.isEmpty()) {
            SPUtils.setString(SP_KEY, id)
        } else {
            getAll()?.let {
                if (it.contains(id)) {
                    it.remove(id)
                }
                it.add(0, id)
                save(it)
            }
        }
    }

    fun delete(id: String) {
        val originString = SPUtils.getString(SP_KEY)
        if (originString.isNotEmpty()) {
            getAll()?.let {
                if (it.contains(id)) {
                    it.remove(id)
                }
                save(it)
            }
        }
    }

    private fun save(it: ArrayList<String>) {
        val builder = StringBuilder()
        for ((index, key) in it.withIndex()) {
            builder.append(key)
            if (index != it.size - 1) {
                builder.append(DIVIDER)
            }
        }
        SPUtils.setString(SP_KEY, builder.toString())
    }

    fun sortForumList(originalForums: ArrayList<ForumEntity>?) {
        if (originalForums.isNullOrEmpty()) return
        val visitRecords = getAll()
        val tempList = arrayListOf<ForumEntity>()
        visitRecords?.forEach { id ->
            val index = originalForums.indexOfFirst { it.id == id }
            if (index >= 0) {
                tempList.add(originalForums.removeAt(index))
            }
        }
        tempList.addAll(originalForums)
        originalForums.clear()
        originalForums.addAll(tempList)
    }

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

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

    companion object {
        private const val SP_KEY = "forum_recoed_key"
        private const val DIVIDER = "<-||->"

        @Volatile
        private var instance: ForumRecordDao? = null

        fun getInstance(): ForumRecordDao {
            return instance ?: synchronized(this) {
                instance ?: ForumRecordDao().also { instance = it }
            }
        }
    }
}