package de.steamwar.tntleague.events

import de.steamwar.tntleague.game.TNTLeagueGame
import de.steamwar.tntleague.plugin
import de.steamwar.tntleague.util.basic
import de.steamwar.tntleague.util.colorByTeam
import de.steamwar.tntleague.util.translate
import de.steamwar.tntleague.util.yellow
import io.papermc.paper.util.Tick
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.block.Action
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.player.PlayerDropItemEvent
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent

object LobbyListener: Listener {

    @EventHandler
    fun onPlayerJoin(e: PlayerJoinEvent) {
        TNTLeagueGame.getFreeTeam()?.run {
            join(e.player)
            TNTLeagueGame.checkStart()
        }
    }

    @EventHandler(priority = EventPriority.LOWEST)
    fun onPlayerQuit(e: PlayerQuitEvent) {
        val team = TNTLeagueGame.getTeam(e.player) ?: return
        team.leave(e.player)
    }

    @EventHandler
    fun onPlayerDamage(e: EntityDamageEvent) {
        e.isCancelled = true
    }

    @EventHandler
    fun onDropEvent(e: PlayerDropItemEvent) {
        e.isCancelled = true
    }

    @EventHandler
    fun interactEvent(e: PlayerInteractEvent) {
        val team = TNTLeagueGame.getTeam(e.player)
        if (e.action.isRightClick && team != null && e.item?.isSimilar(team.readyItem()) == true && team.opposite.leader != null) {
            team.isReady = !team.isReady
        }
    }

    @EventHandler
    fun inventoryClick(e: InventoryClickEvent) {
        if (e.clickedInventory == e.whoClicked.inventory) {
            e.isCancelled = true
        }
    }
}