package co.id.datacomsolusindo.ipphonebridge

import org.springframework.http.HttpHeaders
import java.time.Duration
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import kotlin.concurrent.fixedRateTimer

class ChunkCollector(private val id: String) {
    private val mapSocketChunk: ConcurrentMap<Int, SocketChunkData> by lazy { ConcurrentHashMap() }

    @Synchronized
    fun add(dt: SocketChunkData) {
        mapSocketChunk.getOrPut(dt.part) { dt }
        val listSocketChunk = mapSocketChunk.entries.sortedBy { it.key }.map { it.value }
        if (listSocketChunk.isNotEmpty() && listSocketChunk[0].totalPart == listSocketChunk.size) {
            println("----> $id")
            val sortedChunk = listSocketChunk.sortedBy { it.part }
            val bodyList = sortedChunk.mapNotNull { it.body }
            var bd = ByteArray(0)
            bodyList.forEach { bd += it }
            Singletons.responseQue.getOrPut(id) {
                Resp(
                    bd,
                    sortedChunk.last().status,
                    listSocketChunk.firstOrNull { it.header != null }?.header?.entries?.associate {
                        Pair(it.key, it.value.toTypedArray())
                    }
                )
            }
        }
    }
}

class SocketChunkData(
    val body: ByteArray?,
    val header: HttpHeaders?,
    val status: Int,
    val part: Int,
    val totalPart: Int
)