/*
* This file is part of QTGZManager, an open-source GUI for Slackware pkgtools.
* Copyright (C) 2006  Alexandre Albuquerque Arnt
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
* Contact e-mail : Alexandre Albuquerque Arnt <aaarnt@gmail.com>
* Program URL   : http://jtgzmanager.sf.net
*
*/

#include <QtGui>
#include <QFutureWatcher>
#include "tvpackagesitemdelegate.h"
#include "package.h"
#include "mainwindowimpl.h"

QPoint gPoint;
QFutureWatcher<QString> fw;

using namespace QtConcurrent;

QString showPackageInfo(QString s, bool b){
	return(Package::getInformation(s, b));
}

tvPackagesItemDelegate::tvPackagesItemDelegate(QObject *parent): QItemDelegate(parent){};

bool tvPackagesItemDelegate::helpEvent ( QHelpEvent *event, QAbstractItemView*, 
		const QStyleOptionViewItem&, const QModelIndex &index ){

	if ( ((this->parent()->objectName() == "tvPackage") || (this->parent()->objectName() == "tvInstalledPackages")) 
		&& (index.isValid()) ) {
		QTreeView* tvPackages = qobject_cast<QTreeView*>(this->parent());
		QSortFilterProxyModel *sfp = qobject_cast<QSortFilterProxyModel*>(tvPackages->model());		
		QStandardItemModel *sim = qobject_cast<QStandardItemModel*>(sfp->sourceModel());		
		if (sim->rowCount() == 0) return false;

		QModelIndex ind = sfp->mapToSource(index);
		QStandardItem *si = sim->itemFromIndex(ind);
		SelectedPackage sp;
		if (this->parent()->objectName() == "tvPackage") 
			sp = SelectedPackage( MainWindowImpl::returnMainWindow()->selectedDirectory(), si->text() );
		else sp = SelectedPackage( PACKAGES_DIR, si->text() );		
		
		QPoint p;
		gPoint = tvPackages->mapToGlobal(event->pos()); 
		QFuture<QString> f;
		if (this->parent()->objectName() == "tvPackage") 
			f = run(showPackageInfo, sp.getCompleteFileName(), false);
		else f = run(showPackageInfo, sp.getCompleteFileName(), true);

		fw.setFuture(f);
		connect(&fw, SIGNAL(finished()), this, SLOT(execToolTip()));
	}
	return true;
}

void tvPackagesItemDelegate::execToolTip(){
	gPoint.setX(gPoint.x() + 25);
	gPoint.setY(gPoint.y() + 25);
	QToolTip::showText(gPoint, fw.result());
}
