package de.mydevtime.sponge.plugin.lootchest.listener

import de.mydevtime.sponge.plugin.lootchest.LootChest
import de.mydevtime.sponge.plugin.lootchest.data.Constant
import de.mydevtime.sponge.plugin.lootchest.manager.ChestManager
import org.slf4j.Logger
import org.spongepowered.api.Game
import org.spongepowered.api.block.tileentity.carrier.Chest
import org.spongepowered.api.entity.living.player.Player
import org.spongepowered.api.event.Listener
import org.spongepowered.api.event.filter.cause.First
import org.spongepowered.api.event.filter.cause.Root
import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent
import org.spongepowered.api.event.item.inventory.InteractInventoryEvent
import org.spongepowered.api.item.inventory.type.CarriedInventory


class ChestPreviewListener(val lootChest: LootChest, val game: Game, val logger: Logger, val cm: ChestManager)
{
	@Listener
	fun chestInvInteract(event: ChangeInventoryEvent, @First player: Player)
	{
		if (event.isCancelled)
		{
			return
		}

		if (event.targetInventory is CarriedInventory<*>)
		{
			if (((event.targetInventory as CarriedInventory<*>).carrier).isPresent)
			{
				if (((event.targetInventory as CarriedInventory<*>).carrier).get() is Chest && Constant.LIST_PLAYER_PREVIEW.contains(player))
				{
					val block = (((event.targetInventory as CarriedInventory<*>).carrier).get() as Chest).location.createSnapshot()

					if (cm.isRegistered(block))
					{
						event.isCancelled = true
					}
				}
			}
		}
	}

	@Listener
	fun checkForChestPreviewFinished(event: InteractInventoryEvent.Close, @Root player: Player)
	{
		if (event.isCancelled)
		{
			return
		}

		if (event.targetInventory is CarriedInventory<*>)
		{
			if (((event.targetInventory as CarriedInventory<*>).carrier).isPresent)
			{
				if (((event.targetInventory as CarriedInventory<*>).carrier).get() is Chest && Constant.LIST_PLAYER_PREVIEW.contains(player))
				{
					val block = (((event.targetInventory as CarriedInventory<*>).carrier).get() as Chest).location.createSnapshot()

					if (cm.isRegistered(block))
					{
						Constant.LIST_PLAYER_PREVIEW.remove(player)
					}
				}
			}
		}
	}
}