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

import com.comphenix.tinyprotocol.TinyProtocol;
import de.steamwar.core.Core;
import de.steamwar.linkage.Linked;
import de.steamwar.sql.SWException;
import de.steamwar.techhider.ProtocolUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
import net.minecraft.network.protocol.game.ServerboundUseItemOnPacket;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Linked
public class AntiNocom implements Listener {

    private final Map<Player, Integer> flags = new ConcurrentHashMap<>();

    public AntiNocom() {
        TinyProtocol.instance.addFilter(ServerboundPlayerActionPacket.class, this::onDig);
        registerUseItem();
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent e) {
        flags.remove(e.getPlayer());
    }

    private void registerUseItem() {
        TinyProtocol.instance.addFilter(ServerboundUseItemOnPacket.class, (player, packet) -> {
            BlockPos pos = packet.getHitResult().getBlockPos();
            return isValid(player, "UseItem", pos.getX(), pos.getZ()) ? packet : null;
        });
    }

    private ServerboundPlayerActionPacket onDig(Player player, ServerboundPlayerActionPacket packet) {
        BlockPos pos = packet.getPos();
        return isValid(player, "Dig", pos.getX(), pos.getZ()) ? packet : null;
    }

    private boolean isValid(Player player, String type, int x, int z) {
        if ((x == 0 && z == 0) || player.getWorld().isChunkLoaded(ProtocolUtils.posToChunk(x), ProtocolUtils.posToChunk(z))) {
            return true;
        }

        int amount = flags.compute(player, (p, a) -> a == null ? 1 : a + 1);
        if (amount % 8 == 0) {  // Only after 8 and every 8 to reduce false flags and spam
            if (amount == 8) {
                // Schedule player kick only once
                Bukkit.getScheduler().runTask(Core.getInstance(), () -> player.kickPlayer(null));
            }

            SWException.log(player.getName() + " kicked for potential NoCom-DOS attack", x + " " + z + " " + type + " " + amount);
        }
        return false;
    }
}
