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

#include "selectedtagsview.h"

#include <cassert>
#include <string>

#include <QAbstractItemModel>
#include <QAction>
#include <QContextMenuEvent>
#include <QHeaderView>
#include <QMenu>

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

#include "treefiltermodel.h"

using namespace std;

namespace NTagModel
{

SelectedTagsView::SelectedTagsView(QWidget * parent)
 : QListView(parent), _selectedProxyModel(true, this)
{
// 	_displayedTagsNum = 0;
	connect(this, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(onItemDoubleClicked(const QModelIndex&)));
	// garbage collected
	_pTagListProxyModel = new TagListProxyModel(this);

	QListView::setModel(&_selectedProxyModel);
 	setToolTip(tr("deselect a tag by double-clicking"));
 	setWhatsThis(tr("This list displays the tags currently searched for. "
 		"To remove a tag double-click it."));
}


SelectedTagsView::~SelectedTagsView()
{
}

void SelectedTagsView::setModel(QAbstractItemModel* pModel)
{
	assert(dynamic_cast<VocabularyModel*>(pModel) != 0);
	_pModel = dynamic_cast<VocabularyModel*>(pModel);
 	_pTagListProxyModel->setSourceModel(pModel);
	// we cannot set _pTagListProxyModel as source of _selectedProxyModel earlier,
	// because its source needs to be initialised before (with the vocabulary Model)
	_selectedProxyModel.setSourceModel(_pTagListProxyModel);
	//_selectedProxyModel.setSourceModel(pModel);
	_selectedProxyModel.setDynamicSortFilter(true);
}


void SelectedTagsView::onItemDoubleClicked(const QModelIndex& index )
{
	model()->setData(index, false, SelectedRole);
}

void SelectedTagsView::contextMenuEvent(QContextMenuEvent* pEvent)
{
	QMenu menu(this);
	QModelIndex index = indexAt(pEvent->pos());
	QAction* pClear = menu.addAction(tr("Clear"));
	QAction* pRemove = 0;
	// if the context menu was requested for a tag
	if ( index.isValid() )
	{
		pRemove = menu.addAction(tr("Remove"));
	// not yet
	// 	QAction* pSelectAsUnwanted = menu.addAction("Select as unwanted");
	}
	QAction* pAction = menu.exec(pEvent->globalPos());
	if (pAction)
	{
		if (pAction == pRemove)
			// the index is definitely valid here
			model()->setData(index, false, SelectedRole);
		else if  (pAction == pClear)
		{
			vocabularyModel()->setAllUnselected();
		}
	}
}

}
