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

import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.region.Point;
import de.steamwar.bausystem.region.Region;
import de.steamwar.bausystem.utils.FlatteningWrapper;
import de.steamwar.core.WorldEditRenderer;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.MinVersion;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
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.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
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;
        Selector selector = selectors.get(event.getPlayer());
        if (selector != null) selector.cancel();
        if (!event.getPlayer().isSneaking()) return;
        if (event.getAction() != Action.LEFT_CLICK_BLOCK) return;
        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 class Selector {

        private static final int MAX_BLOCKS = 500_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<>();

        private Region.Area area;

        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();

            Region region = Region.getRegion(block.getLocation());
            area = Region.Area.EMPTY;
            if (region.getBuildArea().inRegion(block.getLocation(), true)) {
                area = region.getBuildArea();
            } else if (region.getTestblockArea().inRegion(block.getLocation(), true)) {
                area = region.getTestblockArea();
            } else if (region.getArea().inRegion(block.getLocation(), true)) {
                area = region.getArea();
            }

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

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

                Point minPoint = new Point(minX, minY, minZ);
                Point maxPoint = new Point(maxX, maxY, maxZ);

                FlatteningWrapper.impl.setSelection(player, minPoint, maxPoint);
                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);
                if (!area.inRegion(block.getLocation(), true)) continue;

                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);
                }
            }
        }
    }
}
