/*
 *   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.FightSystem;
import de.steamwar.fightsystem.states.FightState;
import de.steamwar.fightsystem.states.StateDependentTask;
import de.steamwar.fightsystem.utils.FlatteningWrapper;
import de.steamwar.fightsystem.utils.Region;
import net.md_5.bungee.api.ChatMessageType;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;

import java.util.*;
import java.util.logging.Level;

public class Border {

    private final Map<UUID, Set<Block>> ghostBarriers = new HashMap<>();
    private final Map<UUID, Location> lastLocation = new HashMap<>();
    private final boolean contain;
    private final String resetMessage;
    private final String name;
    private final Region region;
    private final int ghostRange;
    private final int ghostSize;

    public Border(Region region, boolean contain, int ghostRange, String resetMessage, String name) {
        this.contain = contain;
        this.resetMessage = resetMessage;
        this.name = name;
        this.region = region;
        this.ghostRange = ghostRange;
        this.ghostSize = 2 * ghostRange + 1;

        new StateDependentTask(ArenaMode.All, FightState.All, this::run, 1, 1);
    }

    public void addPlayer(Player player) {
        if (ghostBarriers.containsKey(player.getUniqueId())) return;

        ghostBarriers.put(player.getUniqueId(), new HashSet<>());
        lastLocation.put(player.getUniqueId(), player.getLocation());
    }

    public boolean contains(Player player) {
        return ghostBarriers.containsKey(player.getUniqueId());
    }

    public void removePlayer(Player player) {
        lastLocation.remove(player.getUniqueId());
        Set<Block> blocks = ghostBarriers.remove(player.getUniqueId());
        if (blocks == null || !player.isOnline()) return;

        for (Block block : blocks) {
            sendChange(player, block, Material.AIR);
        }
    }

    private void run() {
        List<UUID> offline = new ArrayList<>();
        for (Map.Entry<UUID, Set<Block>> entry : ghostBarriers.entrySet()) {
            UUID uuid = entry.getKey();
            Player player = Bukkit.getPlayer(uuid);
            if (player == null) {
                offline.add(uuid);
                continue;
            }

            Location location = player.getLocation();
            if (region.playerInRegion(location) != contain) {
                player.teleport(lastLocation.get(uuid));
                FightSystem.getMessage().sendPrefixless(resetMessage, player, ChatMessageType.ACTION_BAR);
                return;
            }

            Set<Block> ghostBlocks = entry.getValue();
            Region ghostRegion = Region.fromSize(location.getBlockX() - ghostRange, location.getBlockY() - ghostRange, location.getBlockZ() - ghostRange, ghostSize, ghostSize, ghostSize);
            ghostBlocks.removeIf(block -> {
                if (!ghostRegion.inRegion(block)) {
                    sendChange(player, block, Material.AIR);
                    return true;
                }
                return false;
            });

            if (contain) {
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX() - 1, region.getMinY(), region.getMinZ(), 1, region.getSizeY(), region.getSizeZ()).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMinY() - 1, region.getMinZ(), region.getSizeX(), 1, region.getSizeZ()).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMinY(), region.getMinZ() - 1, region.getSizeX(), region.getSizeY(), 1).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMaxX(), region.getMinY(), region.getMinZ(), 1, region.getSizeY(), region.getSizeZ()).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMaxY(), region.getMinZ(), region.getSizeX(), 1, region.getSizeZ()).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMinY(), region.getMaxZ(), region.getSizeX(), region.getSizeY(), 1).intersection(ghostRegion));
            } else {
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMinY(), region.getMinZ(), 1, region.getSizeY(), region.getSizeZ()).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMinY(), region.getMinZ(), region.getSizeX(), 1, region.getSizeZ()).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMinY(), region.getMinZ(), region.getSizeX(), region.getSizeY(), 1).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMaxX() - 1, region.getMinY(), region.getMinZ(), 1, region.getSizeY(), region.getSizeZ()).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMaxY() - 1, region.getMinZ(), region.getSizeX(), 1, region.getSizeZ()).intersection(ghostRegion));
                borderIteration(player, ghostBlocks, Region.fromSize(region.getMinX(), region.getMinY(), region.getMaxZ() - 1, region.getSizeX(), region.getSizeY(), 1).intersection(ghostRegion));
            }

            lastLocation.put(entry.getKey(), location);
        }

        offline.forEach(uuid -> FightSystem.getPlugin().getLogger().log(Level.INFO, () -> uuid + " was removed from border " + name));
        offline.forEach(ghostBarriers::remove);
        offline.forEach(lastLocation::remove);
    }

    private void borderIteration(Player player, Set<Block> ghostBlocks, Region border) {
        border.forEach((x, y, z) -> {
            Block block = Config.world.getBlockAt(x, y, z);
            if (ghostBlocks.add(block)) {
                sendChange(player, block, Material.BARRIER);
            }
        });
    }

    private void sendChange(Player player, Block block, Material type) {
        if (block.getType() == Material.AIR) {
            FlatteningWrapper.impl.sendBlockChange(player, block, type);
        }
    }
}
