/*------------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


#ifndef	__NMAP__
#define	__NMAP__


		#include "container/nlist.h"
		#include "memory/nauto_ptr.h"


namespace GS {

//
template <class KType, class VType>	struct Pair
{
		KType		key;
		VType		value;

		Pair(const KType _key, const VType _value) : key(_key), value(_value) {}
};

/*!
	@short	Very naive map.
	@todo	Red-black tree.
	@author	Emmanuel Julien (ejulien@nworks.fr)
*/
template <class KType, class VType> class Map
{
		AutoList <Pair <KType, VType> *> pairs;

public:

		Pair <KType, VType> *Get(const KType &key) const
		{
			for	(typename List <Pair <KType, VType> *> ::Item *p = pairs.GetRoot(); p; p = p->Next())
				if	(p->Object()->key == key)
					return p->Object();
			return 0;
		}

		uint		GetCount() const
		{	return pairs.GetCount();	}

		bool		HasKey(const KType &key) const
		{	return asbool(Get(key));	}
		VType		&operator [] (const KType &key) const
		{	return Get(key)->value;		}

		Pair <KType, VType> *Add(const KType &key, const VType &value)
		{
			AutoPtr <Pair <KType, VType> > pair(new Pair <KType, VType> (key, value));
			return pair.IsValid() && pairs.Add(pair) ? pair.Detach() : 0;
		}

		bool		Delete(Pair <KType, VType> *pair)
		{	return pairs.Remove(pair);	}
		bool		Delete(const KType &key)
		{	return Delete(Get(key));	}
};

} // GS


#endif	// __NMAP__