/***************************************************************************
                          ApollonBrowseView.cpp  -  description
                             -------------------
begin		: Dec 05 2003
copyright	: (C) 2002 by Bastiaan Naber, (C) 2002 by Robert Wittams
email		: bastiaan@ricardis.tudelft.nl
description	: 

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kurl.h>

#include <qdir.h>
#include <qlabel.h>
#include <qlistview.h>
#include <qpixmap.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qregexp.h>
#include <qstring.h>
#include <qtooltip.h>

#include <libgift/libgift.h>
#include <libgift/conf.h>

#include "apollonbrowseview.h"
#include "apollonbrowseviewitem.h"
#include "giftconnection.h"

ApollonBrowseView::ApollonBrowseView(QWidget *parent, const int id, const QString &query) :
  QVBox(parent),
  m_id(id),
  m_rootListItem(NULL),
  m_query(query)
{
	m_loader = KGlobal::iconLoader();

	QHBox *box = new QHBox(this);

	m_iconLabel = new QLabel(box);
	m_label = new QLabel(box);

	QString realm;

	m_iconLabel->setPixmap(m_loader->loadIcon("connect_established", KIcon::Small));

	m_labelTextSearch = i18n("Browsing user: <i>%1</i> - Searching...").arg(query);
	m_labelTextComplete = i18n("Browsing user: <i>%1</i> - Search completed!").arg(query);

	m_label->setText(m_labelTextSearch);

	QPushButton *stop = new QPushButton(box);
	stop->setPixmap(m_loader->loadIcon("player_pause", KIcon::Small));
	stop->setFixedHeight(stop->sizeHint().height());
	stop->setFixedWidth(stop->sizeHint().width());
	QToolTip::add(stop, i18n("Stop search"));
	connect(stop, SIGNAL(clicked()), SLOT(stopSearch()));

	QPushButton *close = new QPushButton(box);
	close->setPixmap(m_loader->loadIcon("fileclose", KIcon::Small));
	close->setFixedHeight(close->sizeHint().height());
	close->setFixedWidth(close->sizeHint().width());
	QToolTip::add(close, i18n("Close tab"));
	connect(close, SIGNAL(clicked()), SLOT(deleteThis()));

	box->setStretchFactor(m_label, 4);
	box->setStretchFactor(close, 0);

	m_browseResults = new QListView(this);
	m_browseResults->setSelectionMode(QListView::Extended);

	m_browseResults->addColumn(i18n("Name"));

	m_browseResults->addColumn(i18n("Size"));
	m_browseResults->setColumnWidth(1, 80);
	m_browseResults->setColumnAlignment(1, Qt::AlignRight);

	m_browseResults->setAllColumnsShowFocus(true);
	m_browseResults->setRootIsDecorated(true);
	m_browseResults->setMinimumSize(300, 150);
	m_browseResults->setShowSortIndicator(true);
	m_browseResults->setSorting(1, false);

	connect(m_browseResults, SIGNAL(doubleClicked(QListViewItem *)),
	                         SLOT(itemDoubleClicked(QListViewItem *)));
	connect(m_browseResults, SIGNAL(rightButtonPressed(QListViewItem *, const QPoint &, int)),
	                         SLOT(popUp(QListViewItem *, const QPoint &, int)));

	m_popupMenu = new QPopupMenu(m_browseResults);
	m_popupMenu->insertItem(m_loader->loadIcon("2downarrow", KIcon::Small), i18n("Download"), this, SLOT(download()));

	m_folderPopupMenu = new QPopupMenu(m_browseResults);
	m_folderPopupMenu->insertItem(m_loader->loadIcon("2downarrow", KIcon::Small), i18n("Download folder"), this, SLOT(downloadFolder()));
	m_folderPopupMenu->insertItem(m_loader->loadIcon("2downarrow", KIcon::Small), i18n("Download folder recursively"), this, SLOT(downloadFolderRecursively()));
}

ApollonBrowseView::~ApollonBrowseView()
{
}

void ApollonBrowseView::addItem(QString searchReply)
{
	searchReply = searchReply.stripWhiteSpace();

	QString receivedSearchID = giFTConnection::searchKey("ITEM", searchReply);
	if(receivedSearchID.toInt() == m_id)
	{
		if(searchReply.find("file(") > -1)
		{
			KURL *url = new KURL(giFTConnection::searchKey("url", searchReply));

			if(!m_rootListItem)
			{
				m_rootListItem = new QListViewItem(m_browseResults, url->host());
				m_rootListItem->setPixmap(0, m_loader->loadIcon("connect_established", KIcon::Small));
				m_rootListItem->setOpen(true);
			}

			QString path = url->directory();
			QListViewItem *parent = getParent(path);

			ApollonBrowseViewItem *item = new ApollonBrowseViewItem(parent);

			QString temp = giFTConnection::searchKey("file", searchReply);
			item->setFileName(temp.right(temp.length() - temp.findRev("/") - 1));
			item->setUser(giFTConnection::searchKey("user", searchReply));
			item->setSize(giFTConnection::searchKey("size", searchReply));
			item->setUrl(giFTConnection::searchKey("url", searchReply));
			item->setHash(giFTConnection::searchKey("hash", searchReply));
		}
		else
		{
			QString endSearch = "ITEM(" + QString::number(m_id) + ");";

			if(QString::compare(endSearch, searchReply) == 0)
			{
				m_label->setText(m_labelTextComplete);
			}
		}
	}
}

void ApollonBrowseView::stopSearch()
{
	emit giftCancelBrowseRequest(m_id);
}

void ApollonBrowseView::deleteThis()
{
	// Make a call to the deamon not to search for this one anymore
	emit giftCancelBrowseRequest(m_id);

	delete this;
}

void ApollonBrowseView::downloadItemClicked(QListViewItem *item, bool recursive, QString subdir)
{
	ApollonBrowseViewItem *bvi = dynamic_cast<ApollonBrowseViewItem *>(item);

	if(bvi)
	{
		bvi->setPixmap(0, m_loader->loadIcon("2downarrow", KIcon::Small));

		emit giftAddRequest(bvi->user(), bvi->hash(), bvi->size(), bvi->url(), subdir + bvi->fileName());
	}
	else
	{
		if(m_completed.isEmpty())
		{
			QString home(getenv("HOME"));
			QString filename(home);
			filename.append("/.giFT/giftd.conf");
			Config *config = config_new_ex((char *) filename.ascii(), FALSE);
			m_completed = config_get_str(config, (char *) "download/completed");
			m_completed = m_completed.replace("~", home);
			config_free(config);
		}

		QString dirname = item->text(0);
		item = item->firstChild();
		while(item)
		{
			if(recursive || item->childCount() == 0)
			{
				downloadItemClicked(item, recursive, subdir + dirname + "/");
			}
			item = item->nextSibling();
		}
	}
}

void ApollonBrowseView::itemDoubleClicked(QListViewItem *item)
{
	ApollonBrowseViewItem *bvi = dynamic_cast<ApollonBrowseViewItem*>(item);

	if(bvi)
	{
		bvi->setPixmap(0, m_loader->loadIcon("2downarrow", KIcon::Small));

		emit giftAddRequest(bvi->user(), bvi->hash(), bvi->size(), bvi->url(), bvi->fileName());
	}
}

QListViewItem *ApollonBrowseView::getParent(QString dir)
{
	QListViewItem *parent = m_items[dir];
	if(!parent)
	{
		int index = dir.findRev('/');
		QString dirElement = dir.mid(index + 1);
		QString parentDir = dir.left(index);

		if(parentDir == "")
		{
			QListViewItem *grandParent = m_rootListItem;
			parent = new QListViewItem(grandParent, dirElement);
			parent->setPixmap(0, m_loader->loadIcon("folder", KIcon::Small));

			m_items.insert(dir, parent);
		}
		else
		{
			QListViewItem *grandParent = getParent(parentDir);
			parent = new QListViewItem(grandParent, dirElement);
			parent->setPixmap(0, m_loader->loadIcon("folder", KIcon::Small));

			m_items.insert(dir, parent);
		}
	}

	return parent;
}

void ApollonBrowseView::popUp(QListViewItem *item, const QPoint &point, int /*col*/)
{
	ApollonBrowseViewItem *bvi = dynamic_cast<ApollonBrowseViewItem*>(item);

	if(bvi)
		m_popupMenu->popup(point);
	else
		m_folderPopupMenu->popup(point);
}

void ApollonBrowseView::download()
{
	QListViewItem *item = m_browseResults->firstChild();
	download(item);
}

void ApollonBrowseView::downloadFolder()
{
	QListViewItem *item = m_browseResults->firstChild();
	download(item, false);
}

void ApollonBrowseView::downloadFolderRecursively()
{
	QListViewItem *item = m_browseResults->firstChild();
	download(item, true);
}

void ApollonBrowseView::download(QListViewItem *item, bool recursive)
{
	QListViewItem *child;

	while(item)
	{
		if(item->isSelected())
		{
			downloadItemClicked(item, recursive);
		}

		child = item->firstChild();
		if(child)
		{
			download(child, recursive);
		}

		item = item->nextSibling();
	}
}


#include "apollonbrowseview.moc"

