/***************************************************************************
                          apollonsearchtab.cpp  -  description
                             -------------------
begin		: Dec 05 2003
copyright	: (C) 2005 by Martin Koebele, (C) 2002 by Bastiaan Naber, (C) 2002 by Robert Wittams
email		: martin@mkoebele.de
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 <ktabwidget.h>
#include <kcompletion.h>
#include <klineedit.h>
#include <kcombobox.h>
#include <kdeversion.h>

#include <qlayout.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qpixmap.h>
#include <qvbox.h>
#include <qsizepolicy.h>
 
#include <qtabbar.h>

#include "apollonsearchtab.h"
#include "giftconnection.h"

#define MAX_TABTEXT_CHARS 25

ApollonSearchTab::ApollonSearchTab(QWidget* parent, const char *name, giFTConnection* gcn): ApollonTab(parent, name, gcn)
{

        kqv = static_cast<ApollonQueryView*>(0);
	
	m_hashList = new QValueList<QString>();
	
	KIconLoader *loader = KGlobal::iconLoader();

	splitter = new QVBox(this);

	QWidget* searchpanel = new QWidget(splitter);
	QGridLayout *grid = new QGridLayout(searchpanel, 2, 4, 6);

	QLabel* querylabel = new QLabel(searchpanel);
	querylabel->setText(i18n("Search for "));
	querylabel->setFixedHeight( 20 );

	QLabel* keylabel =   new QLabel(searchpanel);
	keylabel->setText(i18n("with keywords: "));
	keylabel->setFixedHeight( 20 );

	querybox = new KLineEdit(searchpanel);

	KCompletion *comp = querybox->completionObject();
	// Connect to the return pressed signal - optional
 	connect(querybox,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&)));

	// This is a default text to make hacking easier
	//querybox->setText("MTV britney");

	querycombo = new KComboBox(searchpanel);

	querycombo->insertItem(loader->loadIcon("find",KIcon::Small) , i18n("Everything"), 0 );
	querycombo->insertItem(loader->loadIcon("sound",KIcon::Small), i18n("Audio"), 1 );
	querycombo->insertItem(loader->loadIcon("video",KIcon::Small), i18n("Video"), 2 );
	querycombo->insertItem(loader->loadIcon("image",KIcon::Small), i18n("Images"), 3 );
	querycombo->insertItem(loader->loadIcon("txt",KIcon::Small),   i18n("Text documents"), 4 );
	querycombo->insertItem(loader->loadIcon("binary",KIcon::Small),i18n("Software"), 5 );
	querycombo->insertItem(loader->loadIcon("connect_established",KIcon::Small), i18n("User"), 6 );
	/*
	querycombo->insertItem(loader->loadIcon("help_index",KIcon::Small), "hash", 7 );
	*/
	QPushButton* goButton = new QPushButton(searchpanel);
	goButton->setPixmap( loader->loadIcon("ok", KIcon::Toolbar));

	QPushButton* clearButton = new QPushButton(searchpanel);
	clearButton->setPixmap( loader->loadIcon("locationbar_erase", KIcon::Toolbar));

	grid->addWidget(querylabel, 0, 0);
	grid->addWidget(querycombo, 0, 1);
	grid->addWidget(keylabel, 0, 2);
	grid->addWidget(clearButton, 0, 3);	
	grid->addWidget(querybox, 0, 4);
	grid->addWidget(goButton, 0, 5);	
	

	viewtab = new KTabWidget(splitter);

	makePopup();
	clickedTab = NULL;

	connect(viewtab, SIGNAL(currentChanged(QWidget*)), this, SLOT(sltChangeTab(QWidget*)));
	connect(viewtab, SIGNAL(contextMenu(QWidget*,const QPoint&)), this, SLOT(tabContextMenu(QWidget*,const QPoint&)));
	connect( goButton, SIGNAL(clicked()),			this, SLOT(startSearch()) );
	connect( querybox, SIGNAL(returnPressed()), 	this, SLOT(startSearch()) );
	connect(m_gcn, SIGNAL(giftItemReply(QString)), this,SIGNAL(giftItemReply(QString)));
	connect(clearButton, SIGNAL(clicked()), querybox, SLOT(clear()));

	viewtab->setTabPosition(QTabWidget::Top);
	viewtab->setHoverCloseButton( true );
	
	
	closeButton = new QPushButton(viewtab);
	closeButton->setPixmap(loader->loadIcon("tab_remove", KIcon::Small));
	closeButton->setFixedHeight(closeButton->sizeHint().height());
	closeButton->setFixedWidth(closeButton->sizeHint().width());
	connect(closeButton, SIGNAL(clicked()), this, SLOT(closeCurrentTab()));
	QToolTip::add(closeButton, i18n("Close tab (Ctrl-w)"));
	
	viewtab->setCornerWidget(closeButton);
	viewtab->setHidden(true);

#if KDE_IS_VERSION (3,4,0)	
	viewtab->setTabBarHidden(true);
	viewtab->setAutomaticResizeTabs(true);
#else	
	closeButton->setHidden(true);
#endif
}


ApollonSearchTab::~ApollonSearchTab()
{
	closealltabs();
}

void ApollonSearchTab::startQuery(const int &index, const QString &text)
{
	KIconLoader *loader = KGlobal::iconLoader();
	
	int ID = m_gcn->getNewID();

	m_gcn->makeSearchRequest(ID, index, text);

	if(index == 6)
	{
		browseUser(text);
		return;
	}
	else
	{
		kqv = new ApollonQueryView(viewtab, ID, index, text, m_gcn);
		kqv->setHashList(m_hashList);
		connect(this, SIGNAL(sigDeleteHash(QString )), kqv, SLOT(slotDeleteHash(QString)));
	}

	QString tabtext = text;
	tabtext = (tabtext.length() < MAX_TABTEXT_CHARS ) ? tabtext : tabtext.left(MAX_TABTEXT_CHARS - 3).append("...");

	QPixmap icon;

	switch(index)
	{
		case 0:
			icon = loader->loadIcon("find",KIcon::Small);
			break;
		case 1:
			icon = loader->loadIcon("sound",KIcon::Small);
			break;
		case 2:
			icon = loader->loadIcon("video",KIcon::Small);
			break;
		case 3:
			icon = loader->loadIcon("image",KIcon::Small);
			break;
		case 4:
			icon = loader->loadIcon("txt",KIcon::Small);
			break;
		case 5:
			icon = loader->loadIcon("binary",KIcon::Small);
			break;
		/*
		case 6:
			icon = loader->loadIcon("connect_established",KIcon::Small);
			break;
		case 7:
			icon = loader->loadIcon("help_index",KIcon::Small);
			break;
		*/

	}

	viewtab->addTab(kqv, icon, tabtext + i18n(" (searching...)"));
	viewtab->showPage(kqv);
	viewtab->setHidden(false);
#if KDE_IS_VERSION (3,4,0)
	viewtab->setTabBarHidden(false);
#else
        closeButton->setHidden(false);
#endif

	connect(this, SIGNAL(giftItemReply(QString)),                                      kqv,   SLOT(addItem(QString)));
	connect(kqv,  SIGNAL(giftAddRequest(QString, QString, QString, QString, QString)), m_gcn, SLOT(makeAddRequest(QString, QString, QString, QString, QString)));
	connect(kqv,  SIGNAL(giftCancelSearchRequest(int) ),                               m_gcn, SLOT(makeCancelSearchRequest(int)));
	connect(kqv,  SIGNAL(giftBrowseRequest(QString)),                                  this,  SLOT(browseUser(QString)));
	connect(kqv,  SIGNAL(closetabs()),                                                 this,  SLOT(closealltabs()));
}

void ApollonSearchTab::startSearch()
{
	// find out which realm thing is selected and what text is searched for
	int index = querycombo->currentItem();
	QString text = querybox->text();

	startQuery( index, text );
}

void ApollonSearchTab::browseUser(QString string)
{
	KIconLoader *loader = KGlobal::iconLoader();

	int ID = m_gcn->getNewID();

	m_gcn->makeBrowseRequest( ID, string );

	kbv = new ApollonBrowseView( viewtab, ID, string );

	QString tabtext =  string;
	tabtext = (tabtext.length() < MAX_TABTEXT_CHARS ) ? tabtext : tabtext.left(MAX_TABTEXT_CHARS - 3).append("...") ;

	QPixmap icon;
	icon = loader->loadIcon("connect_established",KIcon::Small);

	viewtab->addTab(kbv, icon, tabtext);
	viewtab->showPage(kbv);

	connect( this, SIGNAL(giftItemReply(QString)), kbv, SLOT(addItem(QString)) );
	connect( kbv, SIGNAL( giftAddRequest( QString, QString, QString, QString, QString ) ), m_gcn, SLOT( makeAddRequest( QString, QString, QString, QString, QString ) ) );
	connect( kbv, SIGNAL( giftCancelBrowseRequest(int) ), m_gcn, SLOT( makeCancelBrowseRequest(int) ) );
}


void ApollonSearchTab::sltChangeTab(QWidget *w)
{
	ApollonQueryView *k = dynamic_cast<ApollonQueryView*>(w);
	ApollonBrowseView *b = dynamic_cast<ApollonBrowseView*>(w);
	if(k)
	{
		querybox->setText(k->query());
		querycombo->setCurrentItem(k->index());
		kqv = k;
	}
	if(b)
	{
		querybox->setText(b->query());
		querycombo->setCurrentItem(b->index());
		kbv = b;
	}
}

void ApollonSearchTab::closealltabs()
{
	while((kqv = (ApollonQueryView *) viewtab->child("queryTab")))
	{
		kqv->deleteThis();
	}
#if KDE_IS_VERSION (3,4,0)
	viewtab->setTabBarHidden(true);
#else
        closeButton->setHidden(true);
#endif

}

void ApollonSearchTab::closeThisTab()
{
	if (clickedTab)
		((ApollonQueryView*)clickedTab)->deleteThis();
	
	if (viewtab->currentPage() == 0) {
#if KDE_IS_VERSION (3,4,0)
	        viewtab->setTabBarHidden(true);
#else
        	closeButton->setHidden(true);
#endif

	}
}

void ApollonSearchTab::closeCurrentTab()
{
	ApollonQueryView* tab = dynamic_cast<ApollonQueryView*>(viewtab->currentPage());
	if (tab) {
		tab->deleteThis();
	}
	if (viewtab->currentPage() == 0) {
#if KDE_IS_VERSION (3,4,0)
	        viewtab->setTabBarHidden(true);
#else
        	closeButton->setHidden(true);
#endif

	}
}

void ApollonSearchTab::tabContextMenu( QWidget *target, const QPoint &pos )
{
	clickedTab = target;
	tabmenu->popup(pos);
}

void ApollonSearchTab::makePopup()
{
	KIconLoader* loader = KGlobal::iconLoader();
	tabmenu = new QPopupMenu(this);
	tabmenu->insertItem(loader->loadIcon("tab_remove",  KIcon::Small), i18n("Close Tab (ctrl -w)"), this, SLOT(closeThisTab()));
	tabmenu->insertItem(loader->loadIcon("tab_remove",  KIcon::Small), i18n("Close All Tabs"), this, SLOT(closealltabs()));

}

void ApollonSearchTab::keyPressEvent(QKeyEvent *e)
{
	switch(e->state())
	{
		case ControlButton:
			if(e->key() == Key_W)
			{
				clickedTab = viewtab->currentPage();
				closeThisTab();
			}
			break;

		case NoButton:
			if(e->key() == Key_Escape)
			{
				kqv->stopSearch();
			}
			break;

		default:
			break;
	}
}
void ApollonSearchTab::slotGetHash(QString hash) {
	 *m_hashList << hash;
	 emit sigSendHash(hash); 
}


void ApollonSearchTab::slotDeleteHash(QString hash)
{
	if( m_hashList->remove(hash) )
		emit sigDeleteHash(hash);
}

#include "apollonsearchtab.moc"

