package com.rosetta.messenger.domain.chats.usecase

import javax.inject.Inject

data class SendTypingIndicatorCommand(
    val nowMs: Long,
    val lastSentMs: Long,
    val throttleMs: Long,
    val opponentPublicKey: String?,
    val senderPublicKey: String?,
    val isGroupDialog: Boolean,
    val isOpponentOnline: Boolean
)

data class SendTypingIndicatorDecision(
    val shouldSend: Boolean,
    val nextLastSentMs: Long
)

class SendTypingIndicatorUseCase @Inject constructor() {
    operator fun invoke(command: SendTypingIndicatorCommand): SendTypingIndicatorDecision {
        if (command.nowMs - command.lastSentMs < command.throttleMs) {
            return SendTypingIndicatorDecision(shouldSend = false, nextLastSentMs = command.lastSentMs)
        }

        val opponent = command.opponentPublicKey?.trim().orEmpty()
        val sender = command.senderPublicKey?.trim().orEmpty()
        if (opponent.isBlank() || sender.isBlank()) {
            return SendTypingIndicatorDecision(shouldSend = false, nextLastSentMs = command.lastSentMs)
        }

        if (opponent.equals(sender, ignoreCase = true)) {
            return SendTypingIndicatorDecision(shouldSend = false, nextLastSentMs = command.lastSentMs)
        }

        if (!command.isGroupDialog && !command.isOpponentOnline) {
            return SendTypingIndicatorDecision(shouldSend = false, nextLastSentMs = command.lastSentMs)
        }

        return SendTypingIndicatorDecision(shouldSend = true, nextLastSentMs = command.nowMs)
    }
}
