package fr.koka99cab.spiderman.client.item;

import com.mojang.serialization.MapCodec;
import fr.koka99cab.spiderman.entity.GrapplingHookEntity;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.item.properties.conditional.ConditionalItemModelProperty;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;

public record GrapplingRodCastProperty() implements ConditionalItemModelProperty {
	public static final MapCodec<GrapplingRodCastProperty> MAP_CODEC = MapCodec.unit(new GrapplingRodCastProperty());

	@Override
	public boolean get(ItemStack stack, ClientLevel level, LivingEntity entity, int seed, ItemDisplayContext displayContext) {
		if (!(entity instanceof Player player) || !isHeldStack(player, stack)) {
			return false;
		}

		for (Entity renderedEntity : level.entitiesForRendering()) {
			if (renderedEntity instanceof GrapplingHookEntity hook && hook.getOwner() == player) {
				return true;
			}
		}

		return false;
	}

	@Override
	public MapCodec<GrapplingRodCastProperty> type() {
		return MAP_CODEC;
	}

	private static boolean isHeldStack(Player player, ItemStack stack) {
		return player.getMainHandItem() == stack || player.getOffhandItem() == stack;
	}
}
