package net.taehui.twilight.system

import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import net.taehui.twilight.Logger
import java.io.IOException
import java.nio.file.Paths
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap

object BannedIP : Logger {
    private var bannedIPStore = ConcurrentHashMap<String, LocalDateTime>()

    private fun getJSONMapper(): ObjectMapper {
        val jm = ObjectMapper()
        jm.registerModule(JavaTimeModule())
        return jm
    }

    fun loadBannedIP() {
        try {
            bannedIPStore.putAll(
                getJSONMapper().readValue(
                    Paths.get("Banned IP.json").toFile(),
                    object : TypeReference<ConcurrentHashMap<String, LocalDateTime>>() {})
            )
            logInfo("Loaded Banned IP")
            saveBannedIP()
        } catch (e: IOException) {
            logFault(e)
        }
    }

    fun saveBannedIP() {
        getJSONMapper().writerWithDefaultPrettyPrinter().writeValue(
            Paths.get("Banned IP.json").toFile(),
            bannedIPStore
        )
        logInfo("Saved Banned IP")
    }

    fun putBannedIP(avatarIP: String, date: LocalDateTime) {
        bannedIPStore[avatarIP] = date
    }

    fun wipeBannedIP(avatarIP: String) {
        bannedIPStore.remove(avatarIP)
    }

    fun isBanned(avatarIP: String): Boolean {
        return bannedIPStore.getOrDefault(avatarIP, LocalDateTime.MIN).isAfter(LocalDateTime.now())
    }
}