#ifndef __CBUFFERMANGER_H__
#define __CBUFFERMANGER_H__

#include <Windows.h>
#include < map >

using namespace std;

class CBufferManger
{
public:

	struct chunk
	{
		DWORD	m_dwTimetoDelete;
		DWORD	m_dwID;
		DWORD	m_dwSize;
		BYTE*	m_pAddress;
	};

	CBufferManger(void){};
	~CBufferManger(void)
	{
		//if( m_mapBufferWaitDelete.size() !=
		DWORD dwSize1 = (DWORD)m_mapBufferWaitDelete.size();
		DWORD dwSize2 = (DWORD)m_mapBufferIndex.size();

		chunk* pChunk = NULL;
		for( multimap< DWORD , chunk* >::iterator it = m_mapBufferWaitDelete.begin(); it != m_mapBufferWaitDelete.end(); it++ )
		{
			pChunk = it->second;
			delete [] pChunk->m_pAddress;
		}
	
	};

	BYTE*	Apply	( DWORD dwSize	)
	{
		chunk* pChunk = NULL;
		multimap< DWORD , chunk* >::iterator it = m_mapBufferWaitDelete.lower_bound( dwSize );
		if( it == m_mapBufferWaitDelete.end() )
		{
			pChunk		= new chunk;
			
			pChunk->m_dwSize	= dwSize;
			pChunk->m_pAddress	= new BYTE[ dwSize ];

			m_mapBufferIndex[ pChunk->m_pAddress ] = pChunk;
			return pChunk->m_pAddress;
		}
		else
		{
			pChunk = it->second;
			// 將 Buffer 取出使用
			m_mapBufferWaitDelete.erase( it );
			return pChunk->m_pAddress;
		}
	}

	void	Delete	( BYTE* pAddress )
	{
		chunk* pChunk = NULL;
		map< BYTE* , chunk* >::iterator it = m_mapBufferIndex.find( pAddress );
		if( it != m_mapBufferIndex.end() )
		{
			pChunk						= it->second;
			pChunk->m_dwTimetoDelete	= GetTickCount() + 60000;
			m_mapBufferWaitDelete.insert( multimap< DWORD , chunk* >::value_type( pChunk->m_dwSize , pChunk ) );
		}
	}

	void	Flush()
	{
		// 找出過期的 Chunk 將之刪除

	}

	multimap< DWORD , chunk* >	m_mapBufferWaitDelete;
	map< BYTE* , chunk* >		m_mapBufferIndex;	// 以分配出去的記憶體為索引為主的 map
};

#endif