using Map3DRendering.Common;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Mathematics;

namespace Map3DRendering {
    public class AxesGizmo {
        private Shader axesShader;
        private int vao;

        public AxesGizmo() {
            // Initialisation du shader
            axesShader = new Shader("Shaders/Gizmo/axes.vert", "Shaders/Gizmo/axes.frag");

            // Configuration des données des axes (positions et couleurs)
            float[] axesVertices = {
            // Axe X, rouge
            0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
            1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
            // Axe Y, vert
            0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
            // Axe Z, bleu
            0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f,
            0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
            };

            vao = GL.GenVertexArray();
            int vbo = GL.GenBuffer();
            GL.BindVertexArray(vao);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BufferData(BufferTarget.ArrayBuffer, axesVertices.Length * sizeof(float), axesVertices, BufferUsageHint.StaticDraw);

            // Position attribute
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 6 * sizeof(float), 0);
            GL.EnableVertexAttribArray(0);
            // Color attribute
            GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 6 * sizeof(float), 3 * sizeof(float));
            GL.EnableVertexAttribArray(1);
        }

        public void Render(int windowWidth, int windowHeight, Camera camera) {
            int gizmoSize = 200; // Taille du gizmo en pixels
            GL.Viewport(windowWidth - (gizmoSize + 50), windowHeight - (gizmoSize + 50), gizmoSize, gizmoSize);

            Matrix4 gizmoProjection = Matrix4.CreateOrthographicOffCenter(-1f, 1f, -1f, 1f, 0, 1);

            Matrix4 cameraRotation = camera.GetViewMatrix();
            cameraRotation.Row3 = Vector4.UnitW; // Réinitialise la translation

            axesShader.Use();
            axesShader.SetMatrix4("view", cameraRotation);
            axesShader.SetMatrix4("projection", gizmoProjection);

            GL.BindVertexArray(vao);
            GL.DrawArrays(PrimitiveType.Lines, 0, 6); // 6 points pour les 3 lignes des axes

            GL.Viewport(0, 0, windowWidth, windowHeight); // Rétablissement du viewport principal
        }

    }
}
