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

import de.steamwar.Reflection;
import com.comphenix.tinyprotocol.TinyProtocol;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.CraftbukkitWrapper;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.WorldeditWrapper;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;

import java.util.ArrayList;
import java.util.List;

public class RegionListener implements Listener {

    private final List<Player> signEditing = new ArrayList<>();

    private static final Class<?> updateSign = Reflection.getClass("{nms}.PacketPlayInUpdateSign");
    private static final Class<?> blockPosition = Reflection.getClass("{nms}.BlockPosition");
    private static final Reflection.Field<?> blockPos = Reflection.getField(updateSign, blockPosition, 0);
    private static final Reflection.Field<String[]> signText = Reflection.getField(updateSign, String[].class, 0);
    private static final Class<?> baseBlockPosition = Reflection.getClass("{nms}.BaseBlockPosition");
    private static final Reflection.Field<Integer> blockPosX = Reflection.getField(baseBlockPosition, int.class, 0);
    private static final Reflection.Field<Integer> blockPosY = Reflection.getField(baseBlockPosition, int.class, 1);
    private static final Reflection.Field<Integer> blockPosZ = Reflection.getField(baseBlockPosition, int.class, 2);
    public RegionListener() {
        TinyProtocol.instance.addFilter(updateSign, (player, packet) -> {
            if(!signEditing.contains(player))
                return packet;

            String[] lines = signText.get(packet);
            Object pos = blockPos.get(packet);

            Bukkit.getScheduler().runTask(BauSystem.getPlugin(), () -> {
                Block signLoc = new Location(player.getWorld(), blockPosX.get(pos), blockPosY.get(pos), blockPosZ.get(pos)).getBlock();
                if (!signLoc.getType().name().contains("SIGN"))
                    return;

                Sign sign = ((Sign) signLoc.getState());
                for (int i = 0; i < lines.length; i++) {
                    sign.setLine(i, ChatColor.translateAlternateColorCodes('&', lines[i]));
                }
                sign.update();

                signEditing.remove(player);
            });

            return packet;
        });
    }

    @EventHandler(priority = EventPriority.LOWEST)
    public void playerCommandHandler(PlayerCommandPreprocessEvent e) {
        if (!isWorldEditCommand(e.getMessage().split(" ")[0]))
            return;

        Player p = e.getPlayer();

        if (Welt.noPermission(p, Permission.WORLDEDIT)) {
            p.sendMessage(BauSystem.PREFIX + "§cDu darfst hier kein WorldEdit benutzen");
            e.setCancelled(true);
        }
    }

    private static final String[] shortcutCommands = {"//1", "//2", "//90", "//-90", "//180", "//p", "//c", "//flopy", "//floppy", "//flopyp", "//floppyp", "//u", "//r"};

    private boolean isWorldEditCommand(String command) {
        for (String shortcut : shortcutCommands)
            if (command.startsWith(shortcut))
                return true;

        return WorldeditWrapper.impl.isWorldEditCommand(command);
    }

    @EventHandler
    public void onSignChange(SignChangeEvent event) {
        for (int i = 0; i <= 3; ++i) {
            String line = event.getLine(i);
            if (line == null)
                continue;
            line = ChatColor.translateAlternateColorCodes('&', line);
            event.setLine(i, line);
        }
    }

    @EventHandler
    public void editSign(PlayerInteractEvent event) {
        if (event.getAction() != Action.RIGHT_CLICK_BLOCK ||
                !event.getClickedBlock().getType().name().contains("SIGN") ||
                !event.getPlayer().isSneaking() ||
                (event.getItem() != null && event.getItem().getType() != Material.AIR))
            return;

        Player player = event.getPlayer();
        Sign sign = (Sign) event.getClickedBlock().getState();
        String[] lines = sign.getLines();
        for (int i = 0; i < lines.length; i++) {
            sign.setLine(i, lines[i].replace('\u00A7' /* WINDOWS \u00A7 -> § */, '&'));
        }
        sign.update();

        CraftbukkitWrapper.impl.openSignEditor(player, event.getClickedBlock().getLocation());
        signEditing.add(player);
    }
}
