/*
 *   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.Config;
import de.steamwar.fightsystem.states.FightState;
import de.steamwar.fightsystem.states.StateDependentListener;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.PistonMoveReaction;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPistonEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;

import java.util.Set;
import java.util.function.Consumer;

public class PistonListener implements Listener {

    private final Consumer<BlockPistonEvent> leftAreaHandler;

    public PistonListener(Set<ArenaMode> condition, Consumer<BlockPistonEvent> leftAreaHandler) {
        this.leftAreaHandler = leftAreaHandler;
        if (!condition.contains(Config.mode)) return;

        //Wenn Entern aktiv ist, sollen Raketen etc. entern können
        new StateDependentListener(!Config.GameModeConfig.Arena.AllowMissiles, FightState.All, this);
        new StateDependentListener(Config.GameModeConfig.Arena.AllowMissiles, FightState.Setup, this);
    }

    @EventHandler
    public void handlePistonExtend(BlockPistonExtendEvent e) {
        if (!Config.ArenaRegion.inRegion(e.getBlock())) return;

        BlockFace face = e.getDirection();
        for (Block block : e.getBlocks()) {
            Block target = block.getRelative(face);
            if (!Config.BlueExtendRegion.inRegion(target) && !Config.RedExtendRegion.inRegion(target) && block.getPistonMoveReaction() != PistonMoveReaction.BREAK) {
                leftAreaHandler.accept(e);
                return;
            }
        }
    }

    @EventHandler
    public void handlePistonRetract(BlockPistonRetractEvent e) {
        if (!Config.ArenaRegion.inRegion(e.getBlock())) return;

        for (Block block : e.getBlocks()) {
            if (!Config.BlueExtendRegion.inRegion(block) && !Config.RedExtendRegion.inRegion(block)) {
                leftAreaHandler.accept(e);
                return;
            }
        }
    }
}
