package com.seven.ikar.kotlin.feature.chat

import android.content.Context
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
data class SavedChatScrollPosition(
    val rowKey: String? = null,
    val itemIndex: Int = 0,
    val itemScrollOffset: Int = 0
)

class ChatScrollStateStore(
    context: Context,
    private val json: Json
) {
    private val preferences =
        context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)

    fun read(chatId: String): SavedChatScrollPosition? {
        val raw = preferences.getString(key(chatId), null) ?: return null
        return runCatching {
            json.decodeFromString<SavedChatScrollPosition>(raw)
        }.getOrNull()
    }

    fun save(chatId: String, position: SavedChatScrollPosition) {
        preferences.edit()
            .putString(key(chatId), json.encodeToString(SavedChatScrollPosition.serializer(), position))
            .apply()
    }

    fun clear(chatId: String) {
        preferences.edit().remove(key(chatId)).apply()
    }

    private fun key(chatId: String): String = "scroll_$chatId"

    private companion object {
        private const val PREFERENCES_NAME = "ikar_kotlin_chat_scroll"
    }
}
