/*
 *   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 com.sk89q.worldedit.WorldEditException;
import de.steamwar.fightsystem.ArenaMode;
import de.steamwar.fightsystem.Config;
import de.steamwar.fightsystem.FightSystem;
import de.steamwar.fightsystem.fight.Fight;
import de.steamwar.fightsystem.fight.FightTeam;
import de.steamwar.fightsystem.states.FightState;
import de.steamwar.fightsystem.states.OneShotStateDependent;
import de.steamwar.fightsystem.states.StateDependentListener;
import de.steamwar.fightsystem.utils.FlatteningWrapper;
import de.steamwar.fightsystem.utils.Region;
import de.steamwar.fightsystem.utils.WorldeditWrapper;
import de.steamwar.linkage.Linked;
import de.steamwar.sql.SchematicNode;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.util.Vector;

import java.util.HashSet;
import java.util.Set;

@Linked
public class PrepareSchem implements Listener {

    private final Set<Vector> stationaryMovingPistons = new HashSet<>();

    public PrepareSchem() {
        new OneShotStateDependent(ArenaMode.Prepare, FightState.PostSchemSetup, () -> Bukkit.getScheduler().runTaskLater(FightSystem.getPlugin(), () -> {
            stationaryMovingPistons.clear();
            Fight.getUnrotated().getSchemRegion().forEach((x, y, z) -> {
                if (FlatteningWrapper.impl.checkPistonMoving(Config.world.getBlockAt(x, y, z))) {
                    stationaryMovingPistons.add(new Vector(x, y, z));
                }
            });
        }, 1));

        new StateDependentListener(ArenaMode.Prepare, FightState.Setup, this) {
            @Override
            public void disable() {
                super.disable();
                Region region = Fight.getUnrotated().getExtendRegion();
                int minY = Fight.getUnrotated().getSchemRegion().getMinY();

                SchematicNode schem;
                try {
                    schem = SchematicNode.getSchematicNode(Config.PrepareSchemID);
                } catch (SecurityException e) {
                    FightSystem.getMessage().broadcast("PREPARE_SCHEM_DELETED");
                    Bukkit.shutdown();
                    return;
                }

                try {
                    region.forEach((x, y, z) -> {
                        if (FlatteningWrapper.impl.checkPistonMoving(Config.world.getBlockAt(x, y, z)) && !stationaryMovingPistons.contains(new Vector(x, y, z))) {
                            FightSystem.getMessage().broadcast("PREPARE_ACTIVE_PISTON");
                            Bukkit.shutdown();
                            throw new IllegalStateException();
                        }
                    });
                } catch (IllegalStateException e) {
                    return;
                }

                schem.setSchemtype(Config.GameModeConfig.Schematic.Type.checkType());
                schem.setPrepared(true);

                try {
                    WorldeditWrapper.impl.saveSchem(schem, region, minY);
                } catch (WorldEditException e) {
                    FightSystem.getMessage().broadcast("PREPARE_FAILED_SAVING");
                    Bukkit.shutdown();
                    schem.delete();
                    throw new SecurityException("Could not save schem", e);
                }

                FightSystem.getMessage().broadcast("PREPARE_SENT_IN");
                Bukkit.shutdown();
            }
        };
    }

    @EventHandler
    public void handlePlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        FightTeam team = Fight.getPlayerTeam(player);

        if (team == null) {
            Fight.getUnrotated().addMember(player);
        }

        if (FightState.getFightState() == FightState.PRE_LEADER_SETUP) {
            FightState.setFightState(FightState.PRE_SCHEM_SETUP);
            FightState.setFightState(FightState.POST_SCHEM_SETUP);
        }
    }
}
