/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.fightsystem.listener;

import de.steamwar.fightsystem.ArenaMode;
import de.steamwar.fightsystem.fight.Fight;
import de.steamwar.fightsystem.states.FightState;
import de.steamwar.fightsystem.states.StateDependentListener;
import de.steamwar.linkage.Linked;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryType;

import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;

@Linked
public class InFightInventory implements Listener {

    private static final Set<Material> allowed = Collections.unmodifiableSet(EnumSet.of(Material.TNT, Material.AIR));

    public InFightInventory() {
        new StateDependentListener(ArenaMode.AntiReplay, FightState.Ingame, this);
    }

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        if (!Fight.fighting(event.getWhoClicked())) return;

        InventoryType top = event.getView().getTopInventory().getType();
        if (top == InventoryType.CRAFTING) return;

        if ((event.getCursor() != null && !allowed.contains(event.getCursor().getType())) || (event.getCurrentItem() != null && !allowed.contains(event.getCurrentItem().getType()))) {
            event.setCancelled(true); // Deny if transferred item is not TNT
        }
    }

    @EventHandler
    public void onInventoryDrag(InventoryDragEvent event) {
        if (!Fight.fighting(event.getWhoClicked())) {
            return;
        }

        if (event.getInventory().getType() != InventoryType.PLAYER) {
            int inventorySize = event.getInventory().getSize();

            for (int i : event.getRawSlots()) {
                if (i < inventorySize) {
                    event.setCancelled(true);
                    break;
                }
            }
        }
    }
}
