package de.steamwar.tntleague.events

import de.steamwar.scoreboard.SWScoreboard
import de.steamwar.tntleague.config.TNTLeagueWorldConfig
import de.steamwar.tntleague.game.TNTLeagueGame
import de.steamwar.tntleague.game.TNTLeagueTeam
import de.steamwar.tntleague.inventory.DealerInventory
import de.steamwar.tntleague.util.TNTLeagueScoreboard
import org.bukkit.GameMode
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.entity.EntityType
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityExplodeEvent
import org.bukkit.event.entity.PlayerDeathEvent
import org.bukkit.event.player.PlayerDropItemEvent
import org.bukkit.event.player.PlayerInteractEntityEvent
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerMoveEvent
import org.bukkit.event.player.PlayerQuitEvent

object IngameListener: Listener {

    @EventHandler
    fun onEntityInteract(e: PlayerInteractEntityEvent) {
        if (e.player.gameMode == GameMode.SPECTATOR) return

        if(e.rightClicked.type == EntityType.VILLAGER) {
            e.isCancelled = true
            e.player.openInventory(DealerInventory(e.player).getInventory())
        }
    }

    @EventHandler
    fun onExplode(e: EntityExplodeEvent) {
        e.blockList().filter { it.type == TNTLeagueWorldConfig.targetMaterial }
            .groupBy { getTeamByTargetLocation(it.location) }
            .filterKeysNotNull()
            .mapValues { it.value.size }
            .forEach { it.key.damagedBlocks += it.value }
    }

    @EventHandler
    fun onJoin(e: PlayerJoinEvent) {
        SWScoreboard.impl.createScoreboard(e.player, TNTLeagueScoreboard(e.player))
    }

    @EventHandler
    fun onMove(e: PlayerMoveEvent) {
        if (TNTLeagueGame.getTeam(e.player) != null) {
             if (e.to.blockX >= TNTLeagueWorldConfig.lobby.blockX && e.to.blockX <= TNTLeagueWorldConfig.lobby.blockX + 1 ||
                 e.to.blockZ >= TNTLeagueWorldConfig.lobby.blockZ && e.to.blockZ <= TNTLeagueWorldConfig.lobby.blockZ + 1) {
                 e.isCancelled = true
             }
        }
    }

    @EventHandler
    fun onDropPickaxe(e: PlayerDropItemEvent) {
        if (e.itemDrop.itemStack.type == Material.DIAMOND_PICKAXE) {
            e.isCancelled = true
        }
    }

    private fun getTeamByTargetLocation(location: Location): TNTLeagueTeam? =
        when (location) {
            in TNTLeagueWorldConfig.redTeam.target -> TNTLeagueGame.redTeam
            in TNTLeagueWorldConfig.blueTeam.target -> TNTLeagueGame.blueTeam
            else -> null
        }

    private fun <K, T> Map<K?, T>.filterKeysNotNull(destination: MutableMap<K, T> = mutableMapOf()): Map<K, T> {
        this.forEach { (t, u) -> if(t != null) destination[t] = u }
        return destination
    }
}