﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace RenderLib
{
    internal class IntBufferRange : BufferRange
    {
        private Dictionary<int, int> updates;
        private int ShaderIndex;
        private int Size;
        internal int Position;

        public IntBufferRange(int address, int bufferBase, int size, int index, IntPtr pointer)
            : base(address, bufferBase, pointer)
        {
            updates = new Dictionary<int, int>();
            ShaderIndex = index;
            Size = size;
            Position = 0;
        }

        public void Enqueue(int position, int val)
        {
            updates[position] = val;
        }

        public void Enqueue(int val)
        {
            updates.Add(Position++, val);
        }

        public void Enqueue(List<int> values)
        {
            for (int i = 0; i < values.Count; i++)
                updates.Add(Position++, values[i]);
        }

        public void Build()
        {
            if (updates.Count > 0)
            {
                
                Write();
                
                CurrentCount = Total;
                updates.Clear();
            }
            LockBuffer();
        }

        private void Write()
        {
            unsafe
            {
                int* gInt = (int*)Pointer;

                foreach (int key in updates.Keys)
                {
                    gInt[key] = updates[key];
                }
            }
        }

        public void Bind()
        {
            GL.BindBufferRange(BufferRangeTarget.ShaderStorageBuffer, ShaderIndex, Address, (IntPtr)Base, (IntPtr)Size);
        }

    }
}
