using GameApp.Entities;
using GameApp.Helper;
using GameApp.Model;
using OpenGL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameApp
{
    class Renderer
    {
        const float FOV = 70;
        const float NEAR_PLANE = 0.1f;
        const float FAR_PLANE = 1000f;

        ProjectionMatrix _projectionMatrix;
        int _clientWidth;
        int _clientHeight;

        float AspectRatio
        {
            get { return (float)_clientWidth / (float)_clientHeight; }
        }

        public Renderer(StaticShader shader, int width, int height)
        {
            SetViewRect(width, height);

            shader.Start();
            shader.loadProjectionMatrix(_projectionMatrix);
            shader.Stop();
        }

        public void SetViewRect(int width, int height)
        {
            if (_clientWidth == width && _clientHeight == height)
            {
                return;
            }

            _clientWidth = width;
            _clientHeight = height;

            createProjectionMatrix();
        }

        public void Prepare()
        {
            Gl.Viewport(0, 0, _clientWidth, _clientHeight);

            Gl.Enable(EnableCap.DepthTest);

            Gl.ClearColor(0, 0, 0, 1); // Clear에 사용할 컬러를 지정
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        }

        public bool IsEnabledDepthTest()
        {
            ulong[] values = new ulong[1];
            Gl.GetIntegerNV((int)GetPName.DepthTest, values);

            return values[0] == 1;
        }

        void createProjectionMatrix()
        {
            _projectionMatrix = new PerspectiveProjectionMatrix(FOV, AspectRatio, NEAR_PLANE, FAR_PLANE);
        }

        public void Render(Entity entity, StaticShader shader)
        {
            TextureModel model = entity.Model;
            RawModel rawModel = model.RawModel;

            Gl.BindVertexArray(rawModel.VaoID);
            Gl.EnableVertexAttribArray(0);
            Gl.EnableVertexAttribArray(1);

            Matrix4x4 transformationMatrix = Maths.createTransformationMatrix(entity.Position, entity.RotX, entity.RotY, entity.RotZ, entity.Scale);
            shader.loadTransformationMatrix(transformationMatrix);

            Gl.ActiveTexture(TextureUnit.Texture0);
            Gl.BindTexture(TextureTarget.Texture2d, model.Texture.ID);
            Gl.DrawElements(PrimitiveType.Triangles, rawModel.VertexCount, DrawElementsType.UnsignedInt, IntPtr.Zero);

            Gl.DisableVertexAttribArray(0);
            Gl.DisableVertexAttribArray(1);
            Gl.BindVertexArray(0);
        }
    }
}
