/*
 *   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.tls;

import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.features.tpslimit.TPSUtils;
import de.steamwar.bausystem.region.Region;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.LinkedInstance;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntitySpawnEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.*;

@Linked
public class TLSListener implements Listener {

    @LinkedInstance
    private BauSystem bauSystem;

    private final Map<Region, List<TNTPrimed>> primedTNT = new HashMap<>();

    private final Set<Region> regionSheduled = new HashSet<>();

    private final Map<Region, Long> regionReferenceTick = new HashMap<>();

    private final Set<Player> listeningPlayers = new HashSet<>();

    private boolean listening = false;

    //TODO: Make adjustable per region
    private final long maxDelay = 120;

    @EventHandler(ignoreCancelled = true)
    public void onTNTSpawn(EntitySpawnEvent event) {
        if (!(event.getEntity() instanceof TNTPrimed tnt)) return;
        if (!listening) return;

        Region eventRegion = Region.getRegion(event.getLocation());

        // Add tnt to the list
        primedTNT.computeIfAbsent(eventRegion, rg -> new ArrayList<>()).add(tnt);

        // Update the relativeTick
        long currentTick = TPSUtils.currentRealTick.get();

        long referenceTick = regionReferenceTick.getOrDefault(eventRegion, 0L);
        if (currentTick - referenceTick > maxDelay) {
            referenceTick = currentTick;
            regionReferenceTick.put(eventRegion, referenceTick);
        }
        long relativeTick = currentTick - referenceTick;

        this.messageNextTick(eventRegion, relativeTick);
    }

    public void messageNextTick(Region region, long relativeTick) {
        /*
         * Some TNT can be spawned so late in the gt, that they do not get processed,
         * essentially lengthening their fuse by 1gt. To detect this, shedule the
         * message at the start of the next (server side) gt. If the tnt got processed it has a
         * Fuse of 79, else 80.
         */

        if (!regionSheduled.add(region)) {
            return;
        }

        Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> messagePlayer(region, relativeTick), 1);
    }

    private void messagePlayer(Region region, long relativeTick) {

        regionSheduled.remove(region);

        int primed80 = 0;
        int primed79 = 0;
        for (TNTPrimed tnt : primedTNT.getOrDefault(region, Collections.emptyList())) {
            if (tnt.getFuseTicks() == 80) {
                primed80++;
            } else if (tnt.getFuseTicks() == 79) {
                primed79++;
            }
        }
        primedTNT.remove(region);

        /*
         * Message the player, if there are tnt with Fuse 80 use special message
         */
        for (Player p : listeningPlayers) {
            if (region.getArea().inRegion(p.getLocation(), false)) {
                if (primed80 > 0) {
                    BauSystem.MESSAGE.sendPrefixless("TLS_MESSAGE_80", p, relativeTick, primed79 + primed80, primed80);
                } else {
                    BauSystem.MESSAGE.sendPrefixless("TLS_MESSAGE_79", p, relativeTick, primed79);
                }
            }
        }
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        stopListening(event.getPlayer());
    }

    public void startListening(Player player) {
        listeningPlayers.add(player);
        this.listening = true;
    }

    public void stopListening(Player player) {
        listeningPlayers.remove(player);
        if (listeningPlayers.isEmpty()) {
            this.listening = false;
        }
    }

    public boolean isActiveFor(Player player) {
        return listeningPlayers.contains(player);
    }
}
