package net.taehui.twilight.system

import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import net.taehui.twilight.Avatar
import net.taehui.twilight.Logger
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArraySet

object AvatarIPSystem : Logger {
    private var avatarIPStore = ConcurrentHashMap<String, CopyOnWriteArraySet<String>>()

    fun loadAvatarIP() {
        try {
            avatarIPStore.putAll(
                ObjectMapper().readValue(
                    Paths.get("Avatar IP.json").toFile(),
                    object : TypeReference<ConcurrentHashMap<String, CopyOnWriteArraySet<String>>>() {})
            )
            logInfo("Loaded Avatar IP")
            saveAvatarIP()
        } catch (e: IOException) {
            logFault(e)
        }
    }

    fun saveAvatarIP() {
        Files.newOutputStream(Paths.get("Avatar IP.json"))
            .use { ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(it, avatarIPStore) }
        logInfo("Saved Avatar IP")
    }

    fun putAvatarIP(avatar: Avatar, avatarID: String) {
        if (!avatar.isAwilight) {
            avatarIPStore.computeIfAbsent(avatar.remote) {
                CopyOnWriteArraySet()
            }.add(avatarID)
        }
    }

    fun getAvatarID(avatarIP: String): String {
        return (avatarIPStore[avatarIP] ?: emptyList<String>()).joinToString()
    }
}