package top.r3944realms.lib39.mixin.carryon;

import com.llamalad7.mixinextras.sugar.Local;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.ResolvableProfile;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import top.r3944realms.lib39.content.item.DollItem;
import top.r3944realms.lib39.util.GameProfileHelper;
import top.r3944realms.lib39.util.storage.nbt.NBTReader;
import tschipp.carryon.client.render.CarriedObjectRender;
import tschipp.carryon.common.carry.CarryOnData;
import tschipp.carryon.common.carry.CarryOnDataManager;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * The type Mixin carried object render.
 */
@SuppressWarnings("DuplicatedCode")
@Pseudo
@Mixin(value = CarriedObjectRender.class, remap = false)
public class MixinCarriedObjectRender {
    @ModifyVariable(
            method = "drawBlock",
            at = @At(
                    value = "INVOKE",
                    target = "Lnet/minecraft/client/renderer/item/ItemStackRenderState;submit(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/SubmitNodeCollector;III)V",
                    shift = At.Shift.BEFORE
            ),
            ordinal = 0
    )
    private static ItemStack modifyRenderStack(ItemStack renderStack, @Local(argsOnly = true) Player player) {
        if (renderStack.getItem() instanceof DollItem) {
            CarryOnData carry = CarryOnDataManager.getCarryData(player);
            if (carry != null) {
                Optional<CompoundTag> compound = carry.getNbt().getCompound("tile");
                AtomicReference<ResolvableProfile> profileHolder = new AtomicReference<>();
                NBTReader.ofOpt(compound).gameProfile("profile", profileHolder::set);
                if (profileHolder.get() != null) {
                    GameProfileHelper.saveProfileToItemStack(renderStack,profileHolder.get());
                }
            }
        }
        return renderStack;
    }

}
