/*	Copyright (C) 2003-2008 Free Electron Organization
	Any use of this software requires a license.  If a valid license
	was not distributed with this file, visit freeelectron.org. */

#ifndef __data_RecordIndex_h__
#define __data_RecordIndex_h__

namespace fe
{


template <class T>
class RecordIndex : public WatcherI
{
	public:
		typedef std::map<T, Record> t_T_record;
		RecordIndex(const Accessor<T> aKey);
virtual	~RecordIndex(void);

		void	add(const Record &record);
		void	remove(const Record &record);
		Record	lookup(const T &t);
		void	clear(void);

	private:
		std::map<T, Record>		m_table;
		Accessor<T>				m_aKey;
};

template <class T>
RecordIndex<T>::RecordIndex(const Accessor<T> aKey)
{
	m_aKey = aKey;
}

template <class T>
RecordIndex<T>::~RecordIndex(void)
{
}

template <class T>
void RecordIndex<T>::add(const Record &record)
{
	if(m_aKey.check(record))
	{
		m_table[m_aKey(record)] = record;
	}
}

template <class T>
void RecordIndex<T>::remove(const Record &record)
{
	if(m_aKey.check(record))
	{
		typename t_T_record::iterator it = m_table.find(m_aKey(record));
		if(it != m_table.end())
		{
			if(record == it->second)
			{
				m_table.erase(it);
			}
		}
	}
}

template <class T>
void RecordIndex<T>::clear(void)
{
	m_table.clear();
}

template <class T>
Record RecordIndex<T>::lookup(const T &t)
{
	typename t_T_record::iterator it = m_table.find(t);
	if(it == m_table.end())
	{
		Record invalid;
		return invalid;
	}
	else
	{
		return it->second;
	}
}

} /* namespace */

#endif /* __data_RecordIndex_h__ */

