/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2024 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.utils;

import com.comphenix.tinyprotocol.Reflection;
import de.steamwar.bausystem.features.util.NoClipCommand;
import net.minecraft.core.component.DataComponents;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.protocol.game.PacketPlayInSetCreativeSlot;
import net.minecraft.network.protocol.game.PacketPlayOutExplosion;
import net.minecraft.network.protocol.game.PacketPlayOutGameStateChange;
import net.minecraft.server.level.EntityPlayer;
import net.minecraft.server.level.PlayerInteractManager;
import net.minecraft.world.entity.player.EntityHuman;
import net.minecraft.world.entity.player.PlayerAbilities;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.level.EnumGamemode;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_21_R2.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_21_R2.inventory.CraftItemStack;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.util.Optional;

public class NMSWrapper21 implements NMSWrapper {

    private static final Reflection.FieldAccessor<PlayerInteractManager> playerInteractManager = Reflection.getField(EntityPlayer.class, null, PlayerInteractManager.class);

    @Override
    public void setInternalGameMode(Player player, GameMode gameMode) {
        playerInteractManager.get(((CraftPlayer) player).getHandle()).a(EnumGamemode.a(gameMode.getValue()));
    }

    @Override
    public void setSlotToItemStack(Player player, Object o) {
        PacketPlayInSetCreativeSlot packetPlayInSetCreativeSlot = (PacketPlayInSetCreativeSlot) o;
        int index = packetPlayInSetCreativeSlot.b();
        if (index >= 36 && index <= 44) {
            index -= 36;
        } else if (index > 44) {
            index -= 5;
        } else if (index <= 8) {
            index = index - 8 + 36;
        }
        player.getInventory().setItem(index, CraftItemStack.asBukkitCopy(packetPlayInSetCreativeSlot.e()));
        if (index < 9) player.getInventory().setHeldItemSlot(index);
        player.updateInventory();
    }

    private static final Reflection.FieldAccessor<PacketPlayOutGameStateChange.a> gameStateChangeReason = Reflection.getField(NoClipCommand.gameStateChange, PacketPlayOutGameStateChange.a.class, 12);

    @Override
    public void setGameStateChangeReason(Object packet) {
        gameStateChangeReason.set(packet, PacketPlayOutGameStateChange.d);
    }

    private static final Reflection.FieldAccessor<PlayerAbilities> playerAbilities = Reflection.getField(EntityHuman.class, null, PlayerAbilities.class);

    @Override
    public void setPlayerBuildAbilities(Player player) {
        PlayerAbilities abilities = playerAbilities.get(((CraftPlayer) player).getHandle());
        abilities.d = true;
        abilities.e = true;
    }

    @Override
    public Material pathMaterial() {
        return Material.DIRT_PATH;
    }

    private static final int threshold = 2048;

    @Override
    public boolean checkItemStack(ItemStack item) {
        net.minecraft.world.item.ItemStack nmsItem = CraftItemStack.asNMSCopy(item);
        NBTTagCompound tag = nmsItem.a(DataComponents.b, CustomData.a).c();
        if (tag.e("BlockEntityTag")) {
            NBTTagCompound blockTag = tag.p("BlockEntityTag");
            if (blockTag.e("Items")) {
                return drillDown(blockTag.c("Items", 10), 0, 0) > threshold;
            }
        }

        return false;
    }

    private int drillDown(NBTTagList items, int layer, int start) {
        if (layer > 2) return start + threshold;
        int invalid = start;
        for (NBTBase nbtBase : items) {
            if (!(nbtBase instanceof NBTTagCompound slot))
                continue;
            if (slot.e("tag")) {
                invalid += slot.f("Count");
                NBTTagCompound iTag = slot.p("tag");
                if (iTag.e("BlockEntityTag")) {
                    NBTTagCompound blockTag = iTag.p("BlockEntityTag");
                    if (blockTag.e("Items")) {
                        invalid = drillDown(blockTag.c("Items", 10), layer + 1, invalid);
                    }
                }
            }
            if (invalid > threshold)
                break;
        }
        return invalid;
    }

    @Override
    public Object resetExplosionKnockback(Object packet) {
        PacketPlayOutExplosion explosion = (PacketPlayOutExplosion) packet;

        return new PacketPlayOutExplosion(
                explosion.b(),
                Optional.empty(),
                explosion.f(),
                explosion.g()
        );
    }
}
