package com.matt.forgehax.mods;

import com.matt.forgehax.ForgeHax;
import com.matt.forgehax.util.command.Setting;
import com.matt.forgehax.util.entity.EntityUtils;
import com.matt.forgehax.util.entity.LocalPlayerUtils;
import com.matt.forgehax.util.math.VectorUtils;
import com.matt.forgehax.util.mod.Category;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;


@RegisterMod
public class WaifuESP extends ToggleMod {
    public WaifuESP() { super (Category.RENDER, "WaifuESP", false, "overlay cute animes over players"); }

    public final Setting<Boolean> noRenderPlayers = getCommandStub().builders().<Boolean>newSettingBuilder()
            .name("noRenderPlayers")
            .description("render other players")
            .defaultTo(false)
            .build();

    //private final ResourceLocation waifu = new ResourceLocation("textures/forgehax/waifu1.png");
    private ResourceLocation waifu;

    private final String waifuUrl = "https://raw.githubusercontent.com/fr1kin/ForgeHax/master/src/main/resources/assets/minecraft/textures/forgehax/waifu1.png";

    private BufferedImage getImageFromUrl(String link) {
        BufferedImage image = new BufferedImage(128, 128, 1);
        try {
            URL url = new URL(link);
            image = ImageIO.read(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

    private boolean shouldDraw(EntityLivingBase entity) {
        return LocalPlayerUtils.isTargetEntity(entity) || (
                !entity.equals(MC.player) &&
                        EntityUtils.isAlive(entity) &&
                        EntityUtils.isValidEntity(entity) && (
                        EntityUtils.isPlayer(entity))
                );
    }



    @SubscribeEvent(priority = EventPriority.LOWEST)
    public void onRenderGameOverlayEvent (RenderGameOverlayEvent.Text event) {
        for (Entity entity : MC.world.loadedEntityList) {
            if (EntityUtils.isLiving(entity) && shouldDraw((EntityLivingBase) entity)) {
                EntityLivingBase living = (EntityLivingBase) (entity);
                Vec3d bottomVec = EntityUtils.getInterpolatedPos(living, event.getPartialTicks());
                Vec3d topVec = bottomVec.add(new Vec3d(0, (entity.getRenderBoundingBox().maxY - entity.posY), 0));
                VectorUtils.ScreenPos top = VectorUtils._toScreen(topVec.x, topVec.y, topVec.z);
                VectorUtils.ScreenPos bot = VectorUtils._toScreen(bottomVec.x, bottomVec.y, bottomVec.z);
                if (top.isVisible || bot.isVisible) {

                    int height = (bot.y - top.y);
                    int width = height;

                    int x = (int)(top.x - (width / 1.8)); // normally 2.0 but lowering it shifts it to the left
                    int y = top.y;

                    // draw waifu
                    GlStateManager.enableTexture2D(); // not sure if this is necessary
                    MC.renderEngine.bindTexture(waifu);
                    GlStateManager.color(1,1,1);

                    Gui.drawScaledCustomSizeModalRect(x, y, 0, 0, width, height, width, height, width, height);
                    GlStateManager.disableTexture2D();
                }
            }
        }
    }


    @SubscribeEvent
    public void onRenderPlayer(RenderPlayerEvent.Pre event) {
        if(noRenderPlayers.getAsBoolean() && !event.getEntity().equals(MC.player)) {
            event.setCanceled(true);
        }
    }

    @Override
    public void onLoad() {
        MC.addScheduledTask(() -> {
            try {
                BufferedImage image = getImageFromUrl(waifuUrl);
                DynamicTexture dynamicTexture = new DynamicTexture(image);
                dynamicTexture.loadTexture(MC.getResourceManager());
                waifu = MC.getTextureManager().getDynamicTextureLocation("WAIFU", dynamicTexture);

            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }
}

@@ -30,43 +30,8 @@
 s;%0A%0A
-import com.matt.forgehax.ForgeHax;%0A
 impo
@@ -1027,16 +1027,17 @@
 .URL;%0A%0A%0A
+%0A
 @Registe
@@ -1452,22 +1452,16 @@
 private 
-final 
 Resource
@@ -1822,37 +1822,11 @@
  = n
-ew BufferedImage(128, 128, 1)
+ull
 ;%0A  
@@ -2504,32 +2504,68 @@
 t.Text event) %7B%0A
+        if (waifu == null) return;%0A%0A
         for (Ent
@@ -3515,95 +3515,8 @@
 ifu%0A
-                    GlStateManager.enableTexture2D(); // not sure if this is necessary%0A
     
@@ -3567,16 +3567,17 @@
 waifu);%0A
+%0A
         
@@ -3613,17 +3613,22 @@
 lor(
-1,1,1
+255,255,255
 );%0A
-%0A
     
@@ -3739,63 +3739,8 @@
 t);%0A
-                    GlStateManager.disableTexture2D();%0A
     
@@ -4162,24 +4162,119 @@
 (waifuUrl);%0A
+                if (image == null) %7B LOGGER.warn(%22Failed to download waifu image%22); return; %7D%0A%0A
             
@@ -4504,17 +4504,16 @@
 xture);%0A
-%0A
         

Fix potential waifuesp crash