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

import android.content.Context
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow

class ChatDraftStore(context: Context) {
    private val preferences =
        context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
    private val _changes = MutableSharedFlow<Unit>(extraBufferCapacity = 16)

    val changes: SharedFlow<Unit> = _changes

    fun read(chatId: String): String =
        preferences.getString(key(chatId), null).orEmpty()

    fun save(chatId: String, draft: String) {
        val normalizedDraft = draft.take(MAX_DRAFT_LENGTH)
        if (normalizedDraft.isBlank()) {
            clear(chatId)
            return
        }

        preferences.edit()
            .putString(key(chatId), normalizedDraft)
            .apply()
        _changes.tryEmit(Unit)
    }

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

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

    private companion object {
        private const val PREFERENCES_NAME = "ikar_kotlin_chat_drafts"
        private const val MAX_DRAFT_LENGTH = 16_384
    }
}
