using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VisimBox.Renderer.RenderObjects;
using VisiMath;
using VisiMath.Geometry;
using VisimBox.Renderer;
using OpenTK.Graphics.OpenGL;

namespace VisimRenderGL
{
    class GLMesh : Mesh
    {
        protected uint InternalID;

        /// <summary>
        /// Constructs new mesh.
        /// </summary>
        /// <param name="vert">Vertex buffer with vertices</param>
        /// <param name="ind">Indexbuffer, can be null for nonindexed elements</param>
        /// <param name="type">Type of the primitive</param>
        public GLMesh(IVertexBuffer vert, IIndexBuffer ind, PrimitiveTypes type) : base(vert, ind, type)
        {
            if (vert == null)
                throw new ArgumentException("Can't create mesh with null vertices");
            if (!(vert is GLVertexBuffer))
                throw new ArgumentException("Can't create mesh with nonGL vertex buffer");
            if ((ind!= null) && !(ind is GLIndexBuffer))
                throw new ArgumentException("Can't create mesh with nonGL index buffer");
            //todo, check for primitive type

            //todo create vertex array object
            /*
            //create vertex array object
            try
            {
                GL.GenVertexArrays(1, out InternalID);
            }
            catch
            {
            }
            if (InternalID == 0)
            {
                //Vertex arrays are not supported?
                //use fallback
            }
            else
            {
                GL.BindVertexArray(InternalID);
                
                Vertices.BindBuffer();
                GL.EnableVertexAttribArray(0);
                GL.BindVertexArray(0);
            }
            */
        }

        public override void Render(IRenderContext irc)
        {
            if (Indices == null)
            {
                irc.RenderVertexBuffer(Vertices, PrimitiveType);
            }
            else
            {
                irc.RenderIndexedMesh(Vertices, Indices, PrimitiveType);
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            if (InternalID != 0)
            {
                GL.DeleteVertexArrays(1, ref InternalID);
                InternalID = 0;
            }

        }

    }
}
