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

import com.sk89q.worldedit.EmptyClipboardException;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.math.transform.Transform;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.world.World;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.PluginCheck;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.*;
import org.bukkit.util.Vector;

@Linked
@PluginCheck("FastAsyncWorldEdit")
public class WorldEditRenderer implements Listener {

    private static WorldEditRenderer INSTANCE;

    private static final Material WAND = Material.WOODEN_AXE;

    private final WorldEditPlugin we;

    public WorldEditRenderer() {
        INSTANCE = this;
        we = WorldEditWrapper.getWorldEditPlugin();
        Bukkit.getPluginManager().registerEvents(this, Core.getInstance());

        Bukkit.getScheduler().runTaskTimer(Core.getInstance(), () -> {
            for (Player player : Bukkit.getOnlinePlayers()) {
                renderPlayer(player, true);
            }
        }, 20, 20);
    }

    public static void renderPlayer(Player player) {
        WorldEditRenderer.INSTANCE.renderPlayer(player, false);
    }

    private void renderPlayer(Player player, boolean scheduled) {
        LocalSession session = we.getSession(player);
        renderClipboard(player, session, scheduled);
        renderRegion(player, session, scheduled);
    }

    private void renderClipboard(Player player, LocalSession session, boolean scheduled) {
        try {
            Clipboard clipboard = session.getClipboard().getClipboard();
            Vector pos = player.getLocation().toVector();
            Region region = clipboard.getRegion();
            Transform transform = session.getClipboard().getTransform();
            Vector a = WorldEditWrapper.impl.applyTransform(WorldEditWrapper.impl.getMinimum(region).subtract(WorldEditWrapper.impl.getOrigin(clipboard)), transform).add(pos);
            Vector b = WorldEditWrapper.impl.applyTransform(WorldEditWrapper.impl.getMaximum(region).subtract(WorldEditWrapper.impl.getOrigin(clipboard)), transform).add(pos);
            a = new Vector(a.getBlockX(), a.getBlockY(), a.getBlockZ());
            b = new Vector(b.getBlockX(), b.getBlockY(), b.getBlockZ());
            drawCuboid(Vector.getMinimum(a, b), Vector.getMaximum(a, b), scheduled, true, player);
        } catch (EmptyClipboardException e) {
            WorldEditRendererWrapper.impl.hide(player, true, true);
        }
    }

    private void renderRegion(Player player, LocalSession session, boolean scheduled) {
        World world = session.getSelectionWorld();
        if (world != null) {
            RegionSelector regionSelector = session.getRegionSelector(world);
            try {
                Region region = regionSelector.getRegion();
                drawCuboid(WorldEditWrapper.impl.getMinimum(region), WorldEditWrapper.impl.getMaximum(region), scheduled, false, player);
            } catch (IncompleteRegionException e) {
                WorldEditRendererWrapper.impl.hide(player, false, true);
            }
        }
    }

    private void drawCuboid(Vector min, Vector max, boolean scheduled, boolean clipboard, Player owner) {
        //noinspection deprecation
        if (owner.getItemInHand().getType() != WAND) {
            WorldEditRendererWrapper.impl.hide(owner, true, true);
            WorldEditRendererWrapper.impl.hide(owner, false, true);
        } else {
            WorldEditRendererWrapper.impl.hide(owner, true, WorldEditRendererCUIEditor.Type.CLIPBOARD.getMaterial(owner) == Material.BARRIER);
            WorldEditRendererWrapper.impl.hide(owner, false, WorldEditRendererCUIEditor.Type.SELECTION.getMaterial(owner) == Material.BARRIER);
            WorldEditRendererWrapper.safeDraw(owner, scheduled, clipboard, min, max);
        }
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        if (event.getPlayer().getItemInHand().getType() == WAND) {
            WorldEditRendererWrapper.impl.tick(event.getPlayer());
        }
        renderClipboard(event.getPlayer(), we.getSession(event.getPlayer()), false);
    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> {
            renderRegion(event.getPlayer(), we.getSession(event.getPlayer()), false);
        }, 0);
    }

    @EventHandler
    public void onBlockBreak(BlockBreakEvent event) {
        Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> {
            renderRegion(event.getPlayer(), we.getSession(event.getPlayer()), false);
        }, 0);
    }

    @EventHandler
    public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
        if (event.getMessage().startsWith("//")) {
            Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> {
                LocalSession session = we.getSession(event.getPlayer());
                renderRegion(event.getPlayer(), session, false);
                renderClipboard(event.getPlayer(), session, false);
            }, 5);
        }
    }

    @EventHandler
    public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) {
        Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> {
            renderPlayer(event.getPlayer(), false);
        }, 1);
    }

    @EventHandler
    public void onPlayerDropItem(PlayerDropItemEvent event) {
        renderPlayer(event.getPlayer(), false);
    }

    @EventHandler
    public void onPlayerItemHeld(PlayerItemHeldEvent event) {
        Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> {
            renderPlayer(event.getPlayer(), false);
        }, 1);
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        WorldEditRendererWrapper.impl.remove(event.getPlayer());
    }
}
