//
// C++ Implementation: emptytagfilter
//
// Description: 
//
//
// Author: Benjamin Mesing <bensmail@gmx.net>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "emptytagfilter.h"


#include <QVariant>
#include <QTimer>
#include <QDebug>

// NTagModel
#include "vocabularymodel.h"
#include "vocabularymodelrole.h"

// NPlugin
#include "debtagsplugincontainer.h"
#include "debtagshelper.h"

namespace NTagModel {

EmptyTagFilter::EmptyTagFilter(const VocabularyModel* pModel, const Xapian::Database& xapian, QObject* pParent)
 : QSortFilterProxyModel(pParent), _xapian(xapian)
{
	_tagSelectionHasChanged = false;
	_pVocabularyModel = pModel;
	connect(_pVocabularyModel, SIGNAL(selectionChanged()), SLOT(tagSelectionChanged()));
}


EmptyTagFilter::~EmptyTagFilter()
{
}


bool EmptyTagFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
{
	QModelIndex current = sourceModel()->index(sourceRow, 0, sourceParent);

	// facets are always accepted
	if (sourceModel()->data(current, TypeRole).toInt() == FacetTypeItem) 
	{
		return true;
	}
	
	// Also apply filtering if no tags are selected, because there are tags in the vocab
	// which are not used
	//if (_pVocabularyModel->selectedTags().empty())
	//	return true;

//	static set<string> companionTags;
//	if (_tagSelectionHasChanged) {
//		companionTags = ;
//		_tagSelectionHasChanged = false;
//	}
//	if (companionTags.find(tag) == companionTags.end())
//		qDebug("Tag " + toQString(tag.fullname()) + " is hidden as non-companion");
//	else 
//		qDebug("Tag " + toQString(tag.fullname()) + " is shown as companion");
//	return companionTags.find(tag) != companionTags.end();

	
	Xapian::Enquire enq(_xapian);
	set<Tag> includeTags = _pVocabularyModel->selectedTags();
 	Tag tag = sourceModel()->data(current, TagRole).value<TagWrapper>().tag;
	includeTags.insert(tag);
	
	set<string> terms;
	for (set<Tag>::const_iterator it = includeTags.begin(); it != includeTags.end(); ++it)
	{
		terms.insert(string("XT") + *it);
	}
	Xapian::Query query(Xapian::Query::OP_AND, terms.begin(), terms.end());
	enq.set_query(query);
	Xapian::MSet match = enq.get_mset(0, 1);
	return (match.size() != 0);
}


void EmptyTagFilter::tagSelectionChanged()
{
	_tagSelectionHasChanged = true;
	// it is not sufficient to call invalidateFilter() here (QT 4.5) this seems to be a QT bug
	// calling only invalidateFilter() does lead to hidden facets not being displayed as expected
/* Bug description:
[LB] select tag biology:CLUSTAL/ALN, type XML into tag-filter, remove tag XML -> XML facets are no longer shown
  Gives different result with biology:EMBOSSS
  Same goes for: workswith::XML && use::Data Visualisation -> Filter: "compiler" -> remove use::Data vis (compiler should now show devel::compiler but does not)
  */

	invalidate();
}



}	// NTagModel 

