package io.stellarfrontier.stellarplugin.listeners

import com.google.gson.Gson
import io.stellarfrontier.stellarplugin.SocketClient
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.entity.PlayerDeathEvent
import org.bukkit.event.player.AsyncPlayerChatEvent
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.event.player.PlayerTeleportEvent
import java.time.Instant

class GameListener(private val socket: SocketClient) : Listener {
    private val gson = Gson()

    private fun sendEvent(type: String, player: String, uuid: String, content: String, location: String? = null, inventory: List<Map<String, Any>>? = null) {
        val data: MutableMap<String, Any> = mutableMapOf(
            "type" to type,
            "player" to player,
            "uuid" to uuid,
            "content" to content,
            "timestamp" to Instant.now().toString()
        )
        if (location != null) data["location"] = location
        if (inventory != null) data["inventory"] = inventory

        socket.sendSocketEvent("game_event", gson.toJson(data))
    }

    @EventHandler
    fun onChat(event: AsyncPlayerChatEvent) {
        sendEvent("CHAT", event.player.name, event.player.uniqueId.toString(), event.message)
    }

    @EventHandler
    fun onJoin(event: PlayerJoinEvent) {
        sendEvent("JOIN", event.player.name, event.player.uniqueId.toString(), "Joined the server")
    }

    @EventHandler
    fun onQuit(event: PlayerQuitEvent) {
        val inventory = event.player.inventory.contents.filterNotNull().map { item ->
            mapOf("type" to item.type.toString(), "amount" to item.amount)
        }
        sendEvent("QUIT", event.player.name, event.player.uniqueId.toString(), "Left the server", null, inventory)
    }

    @EventHandler
    fun onDeath(event: PlayerDeathEvent) {
        val inventory = event.entity.inventory.contents.filterNotNull().map { item ->
            mapOf("type" to item.type.toString(), "amount" to item.amount)
        }
        sendEvent("DEATH", event.entity.name, event.entity.uniqueId.toString(), event.deathMessage ?: "Died", event.entity.location.toString(), inventory)
    }

    @EventHandler
    fun onTeleport(event: PlayerTeleportEvent) {
        val inventory = event.player.inventory.contents.filterNotNull().map { item ->
            mapOf("type" to item.type.toString(), "amount" to item.amount)
        }
        sendEvent("TELEPORT", event.player.name, event.player.uniqueId.toString(), "Teleported to ${event.to}", event.to.toString(), inventory)
    }
}
