package me.km.networking;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import me.km.utils.ClientReflectionUtils;
import me.km.utils.Mapper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class ItemStackDisplayGui extends AbstractGui {
    private static final ResourceLocation WIDGETS_TEX_PATH =
            new ResourceLocation("textures/gui/widgets.png");

    public final static ItemStackDisplayGui INSTANCE =
            new ItemStackDisplayGui(Minecraft.getInstance());

    private final Minecraft mc;

    private final ItemStack[] icons = new ItemStack[9];
    private boolean inactive = true;

    public ItemStackDisplayGui(Minecraft mc) {
        this.mc = mc;

        for(int i = 0; i < icons.length; i++) {
            icons[i] = ItemStack.EMPTY;
        }
    }

    public void setActive(boolean active) {
        this.inactive = !active;
    }

    public void setIcon(int index, String name) {
        if(index >= 0 && index < 9) {
            Item item = Mapper.getItem(name);
            if(item != null) {
                icons[index] = new ItemStack(item);
            }
        }
    }

    public final void clear() {
        for(int i = 0; i < icons.length; i++) {
            icons[i] = ItemStack.EMPTY;
        }
    }

    @SuppressWarnings("deprecation")
    public void paint(MatrixStack matrixStack, KeyManager km) {
        if(inactive) {
            return;
        }

        int screenWidth = (mc.getMainWindow().getScaledWidth() >> 1) - 91;
        int y = 0;
        if(ClientReflectionUtils.isRenderingBossBar()) {
            y += 20;
        }

        RenderSystem.enableBlend();
        RenderSystem.color4f(1.0f, 1.0f, 1.0f, 1.0f);
        mc.getTextureManager().bindTexture(WIDGETS_TEX_PATH);
        int oldBlitOffset = this.getBlitOffset();
        setBlitOffset(-90);
        blit(matrixStack, screenWidth, y, 0, 0, 182, 22);
        setBlitOffset(oldBlitOffset);

        y += 3;
        ItemRenderer ir = mc.getItemRenderer();
        int i = 0;
        for(int x = 3; x < 164; x += 20) {
            if(!icons[i].isEmpty()) {
                ir.renderItemAndEffectIntoGUI(mc.player, icons[i], screenWidth + x, y);
                ir.renderItemOverlayIntoGUI(this.mc.fontRenderer, icons[i], screenWidth + x, y,
                        km.getKeyDescription(i));
            }
            i++;
        }
        RenderSystem.disableBlend();
    }
}
