package me.km.networking;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import java.util.TreeMap;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.network.play.NetworkPlayerInfo;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class PlayerHeadGui extends AbstractGui {
    public final static PlayerHeadGui INSTANCE = new PlayerHeadGui(Minecraft.getInstance());

    private class HeadData {
        private final float x;
        private final float y;
        private final float width;
        private final float height;
        private final ResourceLocation rl;

        public HeadData(float x, float y, float width, float height, ResourceLocation rl) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.rl = rl;
        }

        @SuppressWarnings("deprecation")
        public void paint(Minecraft mc, MatrixStack matrixStack) {
            RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
            mc.getTextureManager().bindTexture(rl);
            int scaledWidth = mc.getMainWindow().getScaledWidth();
            int scaledHeight = mc.getMainWindow().getScaledHeight();
            int intX = (int) (x * scaledWidth);
            int intY = (int) (y * scaledHeight);
            int intWidth = (int) (width * scaledWidth);
            int intHeight = (int) (height * scaledHeight);
            AbstractGui.blit(matrixStack, intX, intY, intWidth, intHeight, 8.0f, 8.0f, 8, 8, 64,
                    64);
            AbstractGui.blit(matrixStack, intX, intY, intWidth, intHeight, 40.0f, 8.0f, 8, 8, 64,
                    64);
        }
    }

    private final TreeMap<Integer, HeadData> data;
    private final Minecraft mc;

    public PlayerHeadGui(Minecraft mc) {
        this.mc = mc;
        this.data = new TreeMap<>();
    }

    public void add(int i, float x, float y, float width, float height, String name) {
        NetworkPlayerInfo info = this.mc.player.connection.getPlayerInfo(name);
        if(info != null) {
            data.put(i, new HeadData(x, y, width, height, info.getLocationSkin()));
        }
    }

    public void remove(int i) {
        data.remove(i);
    }

    public void clear() {
        data.clear();
    }

    public void paint(MatrixStack matrixStack) {
        data.values().forEach(head -> head.paint(mc, matrixStack));
    }
}
