package wtf.beatrice.retrorender.engine;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;

public class DebugHud {

    private final SpriteBatch batch;
    private final BitmapFont font;

    public DebugHud() {
        batch = new SpriteBatch();

        FreeTypeFontGenerator generator =
            new FreeTypeFontGenerator(Gdx.files.internal("fonts/red-hat-mono.ttf"));
        FreeTypeFontGenerator.FreeTypeFontParameter param =
            new FreeTypeFontGenerator.FreeTypeFontParameter();

        param.size = 10; // size in defined scaled framebuffer
        param.color = Color.WHITE;

        // reduce aliasing and smoothing
        param.mono = true; // 1-bit glyphs, no grayscale AA
        param.hinting = FreeTypeFontGenerator.Hinting.None; // no font hinting
        param.borderWidth = 0.2f;
        param.borderColor = Color.WHITE;
        param.shadowOffsetX = 0;
        param.shadowOffsetY = 0;

        // sample font texture as pixels
        param.minFilter = Texture.TextureFilter.Nearest;
        param.magFilter = Texture.TextureFilter.Nearest;

        font = generator.generateFont(param);
        generator.dispose();
    }

    // render HUD in virtual resolution
    public void render(int width, int height,
                       PerspectiveCamera camera,
                       float yaw, float pitch) {
        // set up orthographic projection matching target size
        batch.getProjectionMatrix().setToOrtho2D(0, 0, width, height);

        batch.begin();

        String fpsText = Gdx.graphics.getFramesPerSecond() + " FPS";
        font.draw(batch, fpsText, 5f, height - 5f);

        if (camera != null) {
            float x = camera.position.x;
            float y = camera.position.y;
            float z = camera.position.z;

            String posText = String.format("X: %.2f  Y: %.2f  Z: %.2f", x, y, z);
            font.draw(batch, posText, 5f, height - 15f);

            String angText = String.format("Yaw: %.1f  Pitch: %.1f", yaw, pitch);
            font.draw(batch, angText, 5f, height - 25f);
        }

        batch.end();
    }

    public void dispose() {
        batch.dispose();
        font.dispose();
    }
}
