/*
 *   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.bausystem.features.cannon;

import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.features.cannon.depth.Depth;
import de.steamwar.bausystem.features.cannon.depth.DepthManager;
import de.steamwar.bausystem.region.Region;
import de.steamwar.linkage.Linked;
import org.bukkit.Bukkit;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.util.Vector;

import java.util.*;
import java.util.stream.Collectors;

@Linked
public class CannonDetector implements Listener {

    private Map<TNTPrimed, Vector> velocities = new HashMap<>();
    private Map<TNTPrimed, Set<UUID>> propulsionOfProjectile = new HashMap<>();

    @EventHandler(priority = EventPriority.LOW)
    public void onEntityExplode(EntityExplodeEvent event) {
        if (!(event.getEntity() instanceof TNTPrimed)) {
            return;
        }

        TNTPrimed tnt = (TNTPrimed) event.getEntity();
        propulsionOfProjectile.remove(tnt);

        DepthManager.update(tnt, event.blockList());

        List<TNTPrimed> tnts = Bukkit.getWorlds().get(0).getEntitiesByClass(TNTPrimed.class)
                .stream()
                .filter(entity -> entity != tnt)
                .filter(entity -> entity.getFuseTicks() > 1)
                .filter(entity -> entity.getLocation().distance(event.getLocation()) <= 8)
                .collect(Collectors.toList());

        if (tnts.isEmpty()) {
            return;
        }

        boolean isEmpty = velocities.isEmpty();
        tnts.forEach(tntPrimed -> {
            velocities.put(tntPrimed, tntPrimed.getVelocity().clone());
            propulsionOfProjectile.computeIfAbsent(tntPrimed, __ -> new HashSet<>()).add(tnt.getUniqueId());
        });

        if (!isEmpty) {
            return;
        }

        BauSystem.runTaskLater(BauSystem.getInstance(), () -> {
            Map<CannonKey, List<TNTPrimed>> grouped = new HashMap<>();
            velocities.forEach((tntPrimed, vector) -> {
                boolean xBiggest = Math.abs(vector.getX()) > Math.abs(vector.getZ());
                boolean zBiggest = Math.abs(vector.getZ()) > Math.abs(vector.getX());
                Vector vec = new Vector(xBiggest ? Math.signum(vector.getX()) : 0, Math.round(vector.getY() * 100), zBiggest ? Math.signum(vector.getZ()) : 0);
                grouped.computeIfAbsent(new CannonKey(propulsionOfProjectile.get(tntPrimed), vec), ignored -> new ArrayList<>()).add(tntPrimed);
            });
            grouped.forEach((cannonKey, tntPrimeds) -> {
                if (tntPrimeds.size() <= 5) return;
                Region region = Region.getRegion(tntPrimeds.get(0).getLocation());
                if (region.getType().isGlobal()) return;
                if (region.getTestblockArea().isEmpty()) return;
                Depth depth = new Depth(region);
                DepthManager.init(tntPrimeds, depth);
            });
            velocities.clear();
        }, 1);
    }
}
