/*------------------------------------------------------------------------------
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
* 
* Distributable under the terms of either the Apache License (Version 2.0) or 
* the GNU Lesser General Public License, as specified in the COPYING file.
------------------------------------------------------------------------------*/
#ifndef _lucene_search_CachingWrapperFilter_
#define _lucene_search_CachingWrapperFilter_

#include "clucene/util/bitset.h"
#include "clucene/index/indexreader.h"
#include "clucene/search/filter.h"

CL_NS_DEF(search)
/**
 * Wraps another filter's result and caches it.  The purpose is to allow
 * filters to implement this and allow itself to be cached. Alternatively,
 * use the CachingWrapperFilter to cache the filter.
 */
class AbstractCachingFilter: public Filter 
{
	class BitSetHolder: LUCENE_BASE{
		bool deleteBs;
	public:
		BitSetHolder(CL_NS(util)::BitSet* bits, bool deleteBs);
		~BitSetHolder();
		CL_NS(util)::BitSet* bits;
	};
	void closeCallback(CL_NS(index)::IndexReader* reader, void* param);
	typedef CL_NS(util)::LHashMap<CL_NS(index)::IndexReader*, 
	  BitSetHolder*, 
	  CL_NS(util)::Compare::Void<CL_NS(index)::IndexReader>,
	  CL_NS(util)::Equals::Void<CL_NS(index)::IndexReader>,
	  CL_NS(util)::Deletor::Object<CL_NS(index)::IndexReader>, 
	  CL_NS(util)::Deletor::Object<BitSetHolder> > CacheType; 

	CacheType cache;

protected:
	AbstractCachingFilter( const AbstractCachingFilter& copy );
	virtual CL_NS(util)::BitSet* doBits( CL_NS(index)::IndexReader* reader ) = 0;
	virtual bool doShouldDeleteBitSet( CL_NS(util)::BitSet* ){ return false; }
	AbstractCachingFilter();
public:
	virtual ~AbstractCachingFilter();

	/** Returns a BitSet with true for documents which should be permitted in
	search results, and false for those that should not. */
	CL_NS(util)::BitSet* bits( CL_NS(index)::IndexReader* reader );
	
	virtual Filter *clone() const = 0;
	virtual TCHAR *toString() = 0;
	
	bool shouldDeleteBitSet( const CL_NS(util)::BitSet* ) const{ return false; }
};

/**
 * Wraps another filter's result and caches it.  The purpose is to allow
 * filters to simply filter, and then wrap with this class to add
 * caching, keeping the two concerns decoupled yet composable.
 */
class CachingWrapperFilter: public AbstractCachingFilter 
{
private:
	Filter* filter;
	bool deleteFilter;
protected:
	CachingWrapperFilter( const CachingWrapperFilter& copy );
	CL_NS(util)::BitSet* doBits( CL_NS(index)::IndexReader* reader );
	bool doShouldDeleteBitSet( CL_NS(util)::BitSet* bits );
public:
	CachingWrapperFilter( Filter* filter, bool deleteFilter=true );
	~CachingWrapperFilter();

	Filter *clone() const;
	TCHAR *toString();
};

CL_NS_END
#endif
