package dev.dfonline.codeclient.mixin.render.hud;

import dev.dfonline.codeclient.OverlayManager;
import dev.dfonline.codeclient.config.Config;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.hud.InGameHud;
import net.minecraft.client.render.RenderTickCounter;
import net.minecraft.text.Text;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Mixin(InGameHud.class)
public abstract class MInGameHud {

    @Shadow
    public abstract TextRenderer getTextRenderer();

    @Inject(method = "render", at = @At("HEAD"))
    private void onRender(DrawContext context, RenderTickCounter tickCounter, CallbackInfo ci) {
        int scaledWidth = context.getScaledWindowWidth();
        int scaledHeight = context.getScaledWindowHeight();

        TextRenderer textRenderer = getTextRenderer();

        List<Text> overlay = new ArrayList<>(List.copyOf(OverlayManager.getOverlayText()));
        Text cpuUsage = OverlayManager.getCpuUsage();
        if (cpuUsage != null && Config.getConfig().CPUDisplayCorner == Config.CPUDisplayCornerOption.TOP_LEFT) {
            if (overlay.isEmpty()) overlay.add(cpuUsage);
            else {
                overlay.add(0, cpuUsage);
                overlay.add(1, Text.empty());
            }
        }
        if (!overlay.isEmpty()) {
            int index = 0;
            for (Text text : overlay) {
                context.drawTextWithShadow(textRenderer, Objects.requireNonNullElseGet(text, () -> Text.literal("NULL")), 30, 30 + (index * 9), -1);
                index++;
            }
        }

        if (cpuUsage != null && Config.getConfig().CPUDisplayCorner != Config.CPUDisplayCornerOption.TOP_LEFT) {
            int margin = 30;
            int x = switch (Config.getConfig().CPUDisplayCorner) {
                case TOP_LEFT, BOTTOM_LEFT -> margin;
                case TOP_RIGHT, BOTTOM_RIGHT -> scaledWidth - margin - textRenderer.getWidth(cpuUsage);
            };
            int y = switch (Config.getConfig().CPUDisplayCorner) {
                case TOP_LEFT, TOP_RIGHT -> margin;
                case BOTTOM_LEFT, BOTTOM_RIGHT -> scaledHeight - margin - 3;
            };
            context.drawTextWithShadow(textRenderer, cpuUsage, x, y, -1);
        }
    }
}
