package dev.meloda.fast.messageshistory

import androidx.compose.ui.text.buildAnnotatedString
import dev.meloda.fast.common.extensions.orDots
import dev.meloda.fast.common.extensions.setValue
import dev.meloda.fast.data.VkMemoryCache
import dev.meloda.fast.messageshistory.model.MessagesHistoryScreenState
import dev.meloda.fast.model.api.domain.VkMessage
import kotlinx.coroutines.flow.MutableStateFlow
import kotlin.math.abs

internal class MessagesHistoryPinnedMessageHandler(
    private val screenState: MutableStateFlow<MessagesHistoryScreenState>
) {
    fun update(pinnedMessage: VkMessage?) {
        if (pinnedMessage == null) {
            screenState.setValue { old ->
                old.copy(
                    pinnedMessage = null,
                    convo = old.convo.copy(
                        pinnedMessage = null,
                        pinnedMessageId = null
                    ),
                    pinnedSummary = null,
                    pinnedTitle = null
                )
            }
            return
        }

        val pinnedUser = VkMemoryCache.getUser(pinnedMessage.fromId)
        val pinnedGroup = VkMemoryCache.getGroup(abs(pinnedMessage.fromId))
        val pinnedTitle = pinnedUser?.fullName ?: pinnedGroup?.name

        val pinnedSummary = buildAnnotatedString {
            pinnedMessage.text?.let(::append) ?: append("...")
        }

        screenState.setValue { old ->
            old.copy(
                pinnedMessage = pinnedMessage,
                convo = old.convo.copy(
                    pinnedMessage = pinnedMessage,
                    pinnedMessageId = pinnedMessage.id
                ),
                pinnedSummary = pinnedSummary,
                pinnedTitle = pinnedTitle.orDots()
            )
        }
    }
}
