﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RenderLib
{
    internal class VertexBufferRange : BufferRange
    {
        private List<Vertex> vertices;

        public VertexBufferRange(int address, int bufferBase, IntPtr pointer)
            : base(address, bufferBase, pointer)
        {
            vertices = new List<Vertex>();
        }

        public void Enqueue(PMesh mesh)
        {
            Enqueue(mesh.Vertices);
        }

        public void Enqueue(Vertex[] verts)
        {
            if (vertices.Count + verts.Length > 50000)
                Build();
            vertices.AddRange(verts);
            Total += verts.Length;
        }


        //public void Bind()
        //{
        //    Build();
        //}

        public void Build()
        {
            if (vertices.Count > 0)
            {
                //GL.BufferSubData(BufferTarget.ArrayBuffer, (IntPtr)(CurrentCount / Vertex.SizeInBytes) , (IntPtr)(vertices.Count * Vertex.SizeInBytes), vertices.ToArray());

                Write();

                CurrentCount = Total;
                vertices.Clear();
            }
        }

        /// <summary>
        /// Writes the vertex data to the buffer.
        /// </summary>
        /// <param name="pointer">Pointer to the mapping for this buffer</param>
        /// <param name="verts">Vertices to be written to buffer</param>
        private void Write()
        {
            unsafe
            {
                Vertex* gVerts = (Vertex*)Pointer;
                for (int i = 0; i != vertices.Count; ++i)
                {
                    gVerts[i + CurrentCount + Base] = vertices[i];
                    var ve = gVerts[0];
                }
            }
            LockBuffer();
        }
    }

}
