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


#ifndef	__NIODATASTORE__
#define	__NIODATASTORE__


		#include "filesystem/io_handle.h"
		#include "container/nlist.h"
		#include "nstring/nstring.h"
		#include "thread/mutex.h"
		#include "unit/nunit.h"


namespace GS {
	namespace IO {

/*!
	@short Data store.
*/
class	DataStore
{
		Threading::Mutex mutex;

		SharedPtr <Base> io;
		size_t		limit;

		uint		id_seed;
		String		GetNewId();

public:

	struct	Entry
	{
		String		id;
		size_t		size;
		String		user;

		Entry() : size(0) {}
	};

private:

		AutoList <Entry *> entries;

		Entry		*GetEntry(const String &id) const;

public:

		Base		*GetIO() const { return io.c_ptr(); }

		const AutoList <Entry *> &GetEntries() const { return entries; }

		/// Reserve space on the store, an empty id is returned if the store is full.
virtual	String		Reserve(size_t size);
		/// Free a store alias.
virtual	bool		Free(const String &id);

		/// Store data on a reserved id.
		bool		Store(const String &id, const void *data, size_t size, const char *user_data = 0);

		/// Get entry size.
		size_t		GetEntrySize(const String &id) const;

		/// Get the current store size.
		size_t		GetStoreSize() const;
		/// Get the store free space size.
		size_t		GetFreeStore() const;

		/// Restore store content from the storage fs.
		bool		Load(const char *path = "store.db");
		/// Save store content to the storage fs.
		bool		Save(const char *path = "store.db");

		DataStore(Base *storage, size_t storage_limit = Units::MB(32)) : io(storage), limit(storage_limit), id_seed(0) {}
};

	}	// IO
}	// GS


#endif	// __NIODATASTORE__
