package net.taehui.twilight.system

import net.taehui.twilight.Logger
import java.time.LocalDateTime
import java.util.concurrent.*

object WitSystem : Logger {
    private val ses: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor {
        Executors.defaultThreadFactory().newThread(it).apply {
            isDaemon = true
        }
    }
    private val witMap =
        ConcurrentHashMap<Any, MutableCollection<Pair<LocalDateTime, (LocalDateTime) -> (() -> Unit)>>>()

    fun dispose() {
        ses.shutdown()
    }

    fun handleLoop(src: Any, date: LocalDateTime, loopCount: Int, toHandle: (LocalDateTime) -> Unit) {
        if (loopCount != 0) {
            witMap.getOrPut(src) {
                CopyOnWriteArrayList()
            }.add(Pair(date.plusSeconds(1)) {
                toHandle(it)
                ({ handleLoop(src, it.plusSeconds(1), loopCount - 1, toHandle) })
            })
        }
    }

    fun wipeWit(src: Any) {
        witMap.remove(src)
    }

    fun handleSystem() {
        ses.scheduleWithFixedDelay({
            val date = LocalDateTime.now()
            witMap.forEach { (_, witValues) ->
                witValues.forEach {
                    if (!date.isBefore(it.first)) {
                        try {
                            it.second(date)()
                        } catch (e: Throwable) {
                            logFault(e)
                        }
                        witValues.remove(it)
                    }
                }
            }
        }, 0, 1, TimeUnit.SECONDS)
    }
}