package com.example.demo.controller

import io.vavr.collection.HashMap
import io.vavr.collection.Map
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.channels.actor
import org.springframework.messaging.rsocket.RSocketRequester

// Message types for counterActor
sealed class Message
data class AddRequester(val requester: RSocketRequester, val clientId: String) : Message()
data class RemoveRequester(val clientId: String) : Message()
data class GetRequesters(val response: CompletableDeferred<Map<String, RSocketRequester>>) : Message()

// This function launches a new  rsocket actor
@ObsoleteCoroutinesApi // Actor API is planned to be overhauled so this annotation is required for now
fun CoroutineScope.rsocketActor() = actor<Message> {
    var requesterMap: Map<String, RSocketRequester> = HashMap.empty() // actor state
    for (msg in channel) { // iterate over incoming messages
        when (msg) {
            is AddRequester -> {
                println("Actor adding requester")
                requesterMap = requesterMap.put(msg.clientId, msg.requester)
            }
            is RemoveRequester -> {
                println("Actor removing requester")
                requesterMap = requesterMap.remove(msg.clientId)
            }
            is GetRequesters -> msg.response.complete(requesterMap)
        }
    }
}