//--------------------------------------
//               PowerUI
//
//        For documentation or 
//    if you have any issues, visit
//        powerUI.kulestar.com
//
//    Copyright  2013 Kulestar Ltd
//          www.kulestar.com
//--------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;

namespace PowerUI{
	
	/// <summary>
	/// A special type of array which is made up of a set of 'blocks'.
	/// Each block consists of a fixed amount of type T elements.
	/// This fixed amount is the block size.
	/// It regulates an internal array and only resizes when necessary.
	/// Example usage: <see cref="PowerUI.DynamicMesh.Vertices"/>
	/// For example, A block size of 4 (e.g. 4 vertices in a square) and a
	/// block count of 3 generates a 12 element array.
	/// </summary>
	
	public class FixedSizeBuffer<T>{
		
		/// <summary>The output array.</summary>
		public T[] Buffer;
		/// <summary>Should this buffer clear?</summary>
		private bool Clear;
		/// <summary>How many T typed objects make up a 'block' in our buffer.</summary>
		public int BlockSize;
		/// <summary>How many blocks are currently in the buffer.</summary>
		public int BlockCount;
		
		
		/// <summary>Creates a new buffer with the given block size - that's
		/// how many T elements form a block.</summary>
		public FixedSizeBuffer(int blockSize){
			BlockSize=blockSize;
		}
		
		
		/// <summary>Creates a new buffer with the given block size - that's
		/// how many T elements form a block.</summary>
		public FixedSizeBuffer(int blockSize,bool clear){
			BlockSize=blockSize;
			Clear=clear;
		}
		
		/// <summary>Resizes the buffer so it matches the given length.</summary>
		public void ResizeMatch(int blockCount,int length){
			
			if(Buffer!=null && Buffer.Length==length){
				return;
			}
			
			// Update blocks:
			BlockCount=blockCount;
			
			// Create it now:
			Buffer=new T[length];
			
		}
		
		/// <summary>Resizes the buffer to make sure the given amount of blocks will fit.</summary>
		/// <param name="blockCount">How many blocks we want in the buffer.</param>
		public void Resize(int blockCount){
			
			if(BlockCount==blockCount && Buffer!=null){
				return;
			}
			
			BlockCount=blockCount;
			
			int newSize=BlockSize*blockCount;
			
			if(Buffer!=null && newSize<Buffer.Length){
				
				if(Clear){
					// Clear the section of the array:
					Array.Clear(Buffer,newSize,Buffer.Length-newSize);
				}
				
				return;
			}
			
			Buffer=new T[newSize];
		}
		
	}
	
}


