package net.taehui.twilight.system

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

object PlatformIDSystem : Logger {
    private var platformIDStore = ConcurrentHashMap<String, String>()

    fun savePlatformID() {
        ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(Paths.get("Platform ID.json").toFile(), platformIDStore)
        logInfo("Saved Platform ID")
    }

    fun loadPlatformID() {
        try {
            platformIDStore.putAll(
                ObjectMapper().readValue(Paths.get("Platform ID.json").toFile(),
                    object : TypeReference<ConcurrentHashMap<String, String>>() {})
            )
            logInfo("Loaded Platform ID")
        } catch (e: IOException) {
            logFault(e)
        }
    }

    fun putPlatformID(platformID: String, avatarID: String) {
        platformIDStore[if (platformID.startsWith("$")) platformID else "$${platformID}"] = avatarID
    }

    fun wipePlatformID(platformID: String) {
        platformIDStore.remove(if (platformID.startsWith("$")) platformID else "$${platformID}")
    }

    fun getAvatarID(platformID: String): String {
        return platformIDStore.getOrDefault(platformID, platformID)
    }
}