package me.eternal.purrfectsnap.core.features.impl

import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.eternal.purrfectsnap.common.data.ContentType
import me.eternal.purrfectsnap.common.data.SocialScope
import me.eternal.purrfectsnap.core.event.events.impl.SendMessageWithContentEvent
import me.eternal.purrfectsnap.core.features.Feature

class ScopeSync : Feature("Scope Sync") {
    companion object {
        private const val DELAY_BEFORE_SYNC = 2000L
    }

    private val updateJobs = mutableMapOf<String, Job>()

    private fun sync(conversationId: String) {
        context.database.getDMOtherParticipant(conversationId)?.also { participant ->
            context.bridgeClient.triggerSync(SocialScope.FRIEND, participant)
        } ?: run {
            context.bridgeClient.triggerSync(SocialScope.GROUP, conversationId)
        }
    }

    override fun init() {
        context.event.subscribe(SendMessageWithContentEvent::class) { event ->
            if (event.messageContent.contentType != ContentType.SNAP) return@subscribe

            event.addCallbackResult("onSuccess") {
                event.destinations.conversations!!.map { it.toString() }.forEach { conversationId ->
                    updateJobs[conversationId]?.also { it.cancel() }

                    updateJobs[conversationId] = (context.coroutineScope.launch {
                        delay(DELAY_BEFORE_SYNC)
                        sync(conversationId)
                    })
                }
            }
        }
    }
}