package co.id.datacomsolusindo.ipphonebridge

import org.springframework.messaging.handler.annotation.DestinationVariable
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.handler.annotation.SendTo
import org.springframework.stereotype.Controller

@Controller
class SocketChecker() {

    @MessageMapping("/hi")
    @SendTo("/topic/healthCheck")
    @Throws(Exception::class)
    fun greeting(message: MutableMap<*, *>): MutableMap<*, *> {
        return if (!ClientHolder.get().containsKey(message["Hi"])) {
            mutableMapOf(Pair("Hi", "I'am Ok"), Pair("dc", message["Hi"]))
        } else {
            mutableMapOf(Pair("Hi", "I'am Ok"))
        }
    }

    fun collectChunk(message: SocketChunkData, id: String) {
        if (message.totalPart == 1) {
//                println("one part only with id $id")
            Singletons.responseQue.getOrPut(id) {
                Resp(
                    message.body,
                    message.status,
                    message.header?.entries?.associate { Pair(it.key, it.value.toTypedArray()) }
                )
            }
        } else {
            val sc = Singletons.buildSocketChunkData.getOrPut(id) { ChunkCollector(id) }
            sc.add(message)
        }
    }

    @MessageMapping("/response/{id}")
    @SendTo("/topic/healthCheck")
    @Throws(Exception::class)
    fun responseMsg(message: SocketChunkData, @DestinationVariable("id") id: String): MutableMap<*, *> {
        try {
            if (Singletons.requestInstance.getOrElse(id) { null } == null) {
                //redirect
//                /app/response/$req-id
            } else {
                collectChunk(message, id)
            }
        } catch (e: Exception) {
            AppLog.write(this.javaClass).error("response error", e)
        }

        return mutableMapOf(Pair("Hi", "I'am Ok"))
    }
}