package me.km.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import me.km.overrides.ModPlayerRenderer;
import static me.km.utils.ReflectionUtils.getField;
import static me.km.utils.ReflectionUtils.getMethod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.overlay.BossOverlayGui;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.client.renderer.entity.PlayerRenderer;
import net.minecraft.entity.Entity;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.apache.logging.log4j.LogManager;

@OnlyIn(Dist.CLIENT)
public class ClientReflectionUtils {
    private final static Method CAN_RENDER_NAME = getMethod(EntityRenderer.class, "func_177070_b", Entity.class);

    public static boolean canRenderName(EntityRenderer lr, Entity liv) {
        try {
            return (boolean) CAN_RENDER_NAME.invoke(lr, liv);
        } catch(Exception ex) {
            LogManager.getLogger().warn("canRenderName - " + ex);
            return false;
        }
    }

    private final static Field BOSS_BAR_MAP = getField(BossOverlayGui.class, "field_184060_g");

    public static boolean isRenderingBossBar() {
        return !ReflectionUtils.getFieldValue(Map.class, Minecraft.getInstance().ingameGUI.getBossOverlay(), BOSS_BAR_MAP).isEmpty();
    }

    private final static Field SKIN_MAP = getField(EntityRendererManager.class, "field_178636_l"); // skinMap
    private final static Field PLAYER_RENDERER = getField(EntityRendererManager.class, "field_178637_m"); // playerRenderer

    public static void updatePlayerRenderer() {
        EntityRendererManager erm = Minecraft.getInstance().getRenderManager();
        ModPlayerRenderer normal = new ModPlayerRenderer(erm, false);
        ModPlayerRenderer slim = new ModPlayerRenderer(erm, true);

        ReflectionUtils.setFieldValue(erm, PLAYER_RENDERER, normal);
        Map<String, PlayerRenderer> map
                = ReflectionUtils.getFieldValue(Map.class, erm, SKIN_MAP);
        map.put("default", normal);
        map.put("slim", slim);
    }
}
