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

import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.world.World;
import de.steamwar.core.WorldEditRenderer;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.MinVersion;
import de.steamwar.teamserver.Builder;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;

import java.util.*;
import java.util.function.Predicate;

@Linked
@MinVersion(20)
public class SelectAdjacent implements Listener {

    private Vector[] FACES = {
            new Vector(1, 0, 0),
            new Vector(-1, 0, 0),
            new Vector(0, 1, 0),
            new Vector(0, -1, 0),
            new Vector(0, 0, 1),
            new Vector(0, 0, -1),

            new Vector(1, 1, 0),
            new Vector(1, -1, 0),
            new Vector(1, 0, 1),
            new Vector(1, 0, -1),
            new Vector(-1, 1, 0),
            new Vector(-1, -1, 0),
            new Vector(-1, 0, 1),
            new Vector(-1, 0, -1),
            new Vector(0, 1, 1),
            new Vector(0, 1, -1),
            new Vector(0, -1, 1),
            new Vector(0, -1, -1),
    };

    private Map<Player, Selector> selectors = new HashMap<>();

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        if (!event.hasItem()) return;
        if (event.getItem().getType() != Material.WOODEN_AXE) return;
        if (!event.getPlayer().isSneaking()) return;
        if (event.getAction() != Action.LEFT_CLICK_BLOCK) return;
        Selector selector = selectors.get(event.getPlayer());
        if (selector != null) selector.cancel();
        Material material = event.getPlayer().getInventory().getItemInOffHand().getType();
        if (material.isAir()) {
            selector = new Selector(event.getClickedBlock(), event.getPlayer(), __ -> true);
        } else {
            selector = new Selector(event.getClickedBlock(), event.getPlayer(), type -> type == material);
        }
        selectors.put(event.getPlayer(), selector);
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        Selector selector = selectors.remove(event.getPlayer());
        if (selector != null) selector.cancel();
    }

    private static final WorldEditPlugin WORLDEDIT_PLUGIN = Objects.requireNonNull((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"));
    private static final World BUKKITWORLD = new BukkitWorld(Bukkit.getWorlds().get(0));

    private class Selector {

        private static final int MAX_BLOCKS = 1_000_000;

        private int minX;
        private int minY;
        private int minZ;
        private int maxX;
        private int maxY;
        private int maxZ;

        private BukkitTask bukkitTask;
        private Predicate<Material> predicate;
        private Set<Location> seen = new HashSet<>();
        private Set<Location> toCalc = new HashSet<>();

        public Selector(Block block, Player player, Predicate<Material> predicate) {
            this.predicate = predicate;
            toCalc.add(block.getLocation());
            minX = block.getX();
            minY = block.getY();
            minZ = block.getZ();
            maxX = block.getX();
            maxY = block.getY();
            maxZ = block.getZ();

            bukkitTask = Bukkit.getScheduler().runTaskTimer(Builder.getInstance(), () -> {
                run();

                long volume = (long)(maxX - minX + 1) * (long)(maxY - minY + 1) * (long)(maxZ - minZ + 1);
                player.sendTitle("", "§e" + volume + " §7Blocks", 0, 5, 0);

                WORLDEDIT_PLUGIN.getSession(player).setRegionSelector(BUKKITWORLD, new CuboidRegionSelector(BUKKITWORLD, BlockVector3.at(minX, minY, minZ), BlockVector3.at(maxX, maxY, maxZ)));
                WorldEditRenderer.renderPlayer(player);

                // boolean finished = toCalc.stream().allMatch(location -> {
                //     return location.getBlockX() >= minX && location.getBlockY() >= minY && location.getBlockZ() >= minZ &&
                //             location.getBlockX() <= maxX && location.getBlockY() <= maxY && location.getBlockZ() <= maxZ;
                // });

                if (toCalc.isEmpty() || seen.size() > MAX_BLOCKS) {
                    bukkitTask.cancel();
                    player.sendTitle("§aDone", "§e" + volume + " §7Blocks", 0, 20, 5);
                }
            }, 1, 1);
        }

        private void cancel() {
            bukkitTask.cancel();
        }

        private void run() {
            Set<Location> current = toCalc;
            toCalc = new HashSet<>();

            for (Location location : current) {
                Block block = location.getBlock();
                if (block.isEmpty() || block.isLiquid()) continue;
                if (!predicate.test(block.getType())) continue;
                seen.add(location);

                minX = Math.min(minX, location.getBlockX());
                maxX = Math.max(maxX, location.getBlockX());
                minY = Math.min(minY, location.getBlockY());
                maxY = Math.max(maxY, location.getBlockY());
                minZ = Math.min(minZ, location.getBlockZ());
                maxZ = Math.max(maxZ, location.getBlockZ());

                for (Vector face : FACES) {
                    Block next = block.getRelative(face.getBlockX(), face.getBlockY(), face.getBlockZ());
                    if (next.isEmpty() || next.isLiquid()) continue;
                    if (!predicate.test(next.getType())) continue;
                    Location loc = next.getLocation();
                    if (seen.contains(loc)) continue;
                    toCalc.add(loc);
                }
            }
        }
    }
}
