package com.example.iot_controlhost.utils.database

import com.example.iot_controlhost.utils.MMKVUtil
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * 消息已读工具类
 */
object MessageReadUtil {

    const val MESSAGE_READ: String = "MESSAGE_READ"

    private val defaultJson: String by lazy {
        Gson().toJson(mapOf<String, Boolean>())
    }

    fun init() {
        MMKVUtil.put<String?>(MESSAGE_READ, defaultJson)
    }

    fun readMessage(messageId: String) {
        val json = MMKVUtil.get<String>(MESSAGE_READ, defaultJson)
        val temp = Gson().fromJson<MutableMap<String, Boolean>>(
            json, object : TypeToken<MutableMap<String, Boolean>>() {}.getType()
        )
        temp.put(messageId, true)
        MMKVUtil.put<String>(MESSAGE_READ, Gson().toJson(temp))
    }

    fun isRead(messageId: String): Boolean {
        val json = MMKVUtil.get<String>(MESSAGE_READ, defaultJson)
        val temp = Gson().fromJson<MutableMap<String, Boolean>>(
            json,
            object : TypeToken<MutableMap<String, Boolean>>() {}.getType()
        )
        return temp.getOrDefault(messageId, false)
    }

}
