package wtf.beatrice.retrorender.engine.render;

public class RetroViewportHelper {

    public static class RetroViewport {
        public int offsetX, offsetY;
        public int drawW, drawH;
        public float scale;
    }

    public static class RetroClick {
        public boolean inside;
        public float x, y; // retro coords
    }

    public static RetroViewport computeViewport(
        int windowW, int windowH,
        int retroW, int retroH) {

        RetroViewport vp = new RetroViewport();

        float scale = Math.min(
            windowW / (float) retroW,
            windowH / (float) retroH
        );

        vp.scale  = scale;
        vp.drawW  = Math.round(retroW * scale);
        vp.drawH  = Math.round(retroH * scale);
        vp.offsetX = (windowW - vp.drawW) / 2;
        vp.offsetY = (windowH - vp.drawH) / 2;

        return vp;
    }

    public static RetroClick toRetroCoords(
        RetroViewport vp,
        int retroW, int retroH,
        int mouseX, int mouseYWindow,
        int windowHeight) {

        RetroClick rc = new RetroClick();
        // libGDX gives mouse from top-left; you already invert Y like this:
        int yBottomOrigin = windowHeight - mouseYWindow;

        if (mouseX < vp.offsetX || mouseX > vp.offsetX + vp.drawW ||
            yBottomOrigin < vp.offsetY || yBottomOrigin > vp.offsetY + vp.drawH) {
            rc.inside = false;
            return rc;
        }

        float relX = (mouseX - vp.offsetX) / (float) vp.drawW;
        float relY = (yBottomOrigin - vp.offsetY) / (float) vp.drawH;

        rc.inside = true;
        rc.x = relX * retroW;
        rc.y = relY * retroH;
        return rc;
    }
}
