#ifdef __UNIT_TEST_PP

#include <UnitTest++.h>
#include <QString>
#include <iostream>
#include <string>
#include <set>

#include <xapian.h>

//#include <debtagsplugin.h>
//#include <debtagsplugincontainer.h>
#include <debtagshelper.h>


using namespace std;

/** @brief Checks if all <em>tags</em> ANDed together give a non-empty result set for
  * ANDed together with each companion. 
  *
  * @param tags may be empty
  * @param companions may be empty
  */
void checkAllGiveNonEmpty(const set<string>& tags, const set<string>& companions, const Xapian::Database& xapian) 
{
	for (set<string>::const_iterator it = companions.begin(); it != companions.end(); ++it)
	{
		set<string> terms;		
		for (set<string>::const_iterator jt = tags.begin(); jt != tags.end(); ++jt)
		{
			terms.insert(string("XT")+(*jt));
		}
		terms.insert(string("XT")+(*it));
		Xapian::Query query(Xapian::Query::OP_AND, terms.begin(), terms.end());
		Xapian::Enquire enq(xapian);
		enq.set_query(query);
		Xapian::MSet match = enq.get_mset(0, 1);
		CHECK(match.size() != 0);
	}
}



TEST(NUtil__companionTags)
{
	using namespace NUtil;
	
	Xapian::Database xapian("/var/lib/apt-xapian-index/index");
	set<string> tags;
	
	set<string> result = companionTags(tags, xapian);
	checkAllGiveNonEmpty(tags, result, xapian);	
	// the number of tags which produce a result should be quite large
	CHECK(result.size() >= 70);
	// the tag implemented-in::c++ should definitely be in there
	CHECK(result.find("implemented-in::c++") != result.end());
	
	tags.insert("implemented-in::c++");
	result = companionTags(tags, xapian);
	checkAllGiveNonEmpty(tags, result, xapian);	
	// there should be quite some tags in the companion set of implemented-in::c++
	CHECK(result.size() >= 10);
	// the tag implemented-in::c++ itself should not be in there
	CHECK(result.find("implemented-in::c++") == result.end());
	// the tag admin::package-management should not be in
	CHECK(result.find("admin::package-management") != result.end());
	
	tags.insert("devel::compiler");
	result = companionTags(tags, xapian);
	checkAllGiveNonEmpty(tags, result, xapian);	
	CHECK(result.size() > 0);

}




/// testing code for NUtil::tagsForPackage()
TEST(NUtil__tagsForPackage)
{
	using namespace NUtil;
	Xapian::Database xapian("/var/lib/apt-xapian-index/index");
	
	set<string> result;
	result = tagsForPackage("", xapian);	// empty package name
	CHECK(result.empty());
	// invalid package name
	result = tagsForPackage("ewkhjgrkleghe", xapian);
	CHECK(result.empty());
	// valid package name
	result = tagsForPackage("packagesearch", xapian);
	CHECK(result.size()>4);
	
	string searching = "use::searching";
	bool foundSearching = false;
	string qt = "uitoolkit::qt";
	bool foundQt = false;
	for (set<string>::const_iterator it = result.begin(); it != result.end(); ++it) 
	{
		if (*it == searching)
			foundSearching = true;
		if (*it == qt)
			foundQt = true;
	}
	CHECK(foundSearching);
	CHECK(foundQt);
}


#endif
