/***************************************************************************
                          dchublistmanager.cpp  -  description
                             -------------------
    begin                : Mon Oct 1 2001
    copyright            : (C) 2001-2004 by Mathias Küster
    email                : mathen@users.berlios.de
 ***************************************************************************/

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

#include <qapplication.h>
#include <qobject.h>
#include <qpainter.h>
#include <qlistview.h>
#include <qpushbutton.h>
#include <qtoolbutton.h>
#include <qlineedit.h>
#include <qpopupmenu.h>
#include <qcursor.h>
#include <qstringlist.h>
#include <qtabwidget.h>
#include <qinputdialog.h>
#include <qcombobox.h>
#include <qregexp.h>
#include <qcheckbox.h>
#include <qmessagebox.h>
#include <qclipboard.h>

#include <dcgeturl.h>
#include <dcclient.h>
#include <dcmenuhandler.h>
#include <dcwidget.h>
#include <dchubprofile.h>
#include <dchubfilter.h>
#include <dciconloader.h>
#include <dcconnectionmanager.h>

#include "dchublistmanager.h"

#include <dclib/dcos.h>
#include <dclib/core/cbz.h>
#include <dclib/chttp.h>

#include "dceditserver.h"
#include "cdialogmessage.h"

DCHubListManager * g_pHubListManager = 0;

/** */
DCHubListManager::DCHubListManager(QWidget* parent, const char *name, int wflags) : DCDialogHubListManager(parent, name, wflags)
{
	int idx;

	// set default icon
	setIcon( g_pIconLoader->GetPixmap(eiSERVER) );

	m_pWorkspace = (QWorkspace*)parent;

	// set the ColumnWidthMode to manual, we will take care of this task
	for( idx = 0; idx < ListView_PUBLIC->columns(); idx++ )
	{
		ListView_PUBLIC->setColumnWidthMode( idx, QListView::Manual );
	}
	for( idx = 0; idx < ListView_BOOKMARKS->columns(); idx++ )
	{
		ListView_BOOKMARKS->setColumnWidthMode( idx, QListView::Manual );
	}

	m_pMessageList = new CList<CObject>();

	InitDocument();

	g_pHubListManager = this;
}

/** */
DCHubListManager::~DCHubListManager()
{
	g_pHubListManager = NULL;

	m_HLMThread.Lock();

	if ( m_pMessageList )
	{
		delete m_pMessageList;
		m_pMessageList = 0;
	}

	m_HLMThread.UnLock();
}

/** current tab widget change slot */
void DCHubListManager::slotTabWidgetCurrentChange(QWidget*)
{
	ResizeListViewColumn();
}

/** overridden so that the columns are resized on show() */
void DCHubListManager::show()
{
	QWidget::show();

	ResizeListViewColumn();
}

/** resize event handler */
void DCHubListManager::resizeEvent( QResizeEvent * )
{
	ResizeListViewColumn();
}

/** resize the ListView columns */
void DCHubListManager::ResizeListViewColumn()
{
	int width;

	if ( ListView_PUBLIC->isVisible() )
	{
		width = ListView_PUBLIC->width();

		ListView_PUBLIC->setColumnWidth( 0, ((width*3)/10) );
		ListView_PUBLIC->setColumnWidth( 1, ((width*3)/10) );
		ListView_PUBLIC->setColumnWidth( 2, ((width*3)/10) );
		ListView_PUBLIC->setColumnWidth( 3, ((width*1)/10) );
	}

	if ( ListView_BOOKMARKS->isVisible() )
	{
		width = ListView_BOOKMARKS->width();

		ListView_BOOKMARKS->setColumnWidth( 0, ((width*10)/30) );
		ListView_BOOKMARKS->setColumnWidth( 1, ((width*10)/30) );
		ListView_BOOKMARKS->setColumnWidth( 2, ((width*10)/30) );
	}
}

/** */
int DCHubListManager::selectedItems( QListView * list, QPtrList<QListViewItem> & lst )
{
	QListViewItemIterator it( (QListView *)list );

	for ( ; it.current(); it++ )
	{
		if ( it.current()->isSelected() )
		{
			lst.append(it.current());
		}
	}

	return lst.count();
}

/** */
void DCHubListManager::SetToolBar( QFrame * frame1, QFrame * frame2, bool vis )
{
	if ( vis )
	{
		frame1->hide();
		frame1->setEnabled(FALSE);
		frame2->show();
		frame2->setEnabled(TRUE);
	}
	else
	{
		frame2->hide();
		frame2->setEnabled(FALSE);
		frame1->show();
		frame1->setEnabled(TRUE);
	}
}

/** */
void DCHubListManager::InitDocument()
{
	StringMap * map;
	bool btb1=TRUE,btb2=TRUE;
	bool bfilter=FALSE;

	DC_HubFilterObject * HubFilterObject;

	// hide progressbar
	ProgressBar_LOADHUBLIST->hide();

	// set bookmark icon
	TabWidget_SERVERLIST->setTabIconSet( TabWidget_SERVERLIST->page(1), QIconSet( g_pIconLoader->GetPixmap(eiBOOKMARK_FOLDER) ) );

	// init the toolbars
	Frame_TOOLBAR1_HIDE->installEventFilter(this);
	Frame_TOOLBAR1_SHOW->installEventFilter(this);
	Frame_TOOLBAR2_HIDE->installEventFilter(this);
	Frame_TOOLBAR2_SHOW->installEventFilter(this);
	
	// restore settings
	if ( g_pConfig->GetMap("HUBVIEW",map) == TRUE )
	{
		if ( ((*map)["WIDTH"].toInt() > 0) && ((*map)["HEIGHT"].toInt() > 0) )
		{
			setGeometry( (*map)["X"].toInt(), (*map)["Y"].toInt(), (*map)["WIDTH"].toInt(), (*map)["HEIGHT"].toInt() );
		}

		if ( ((*map)["TOOLBAR1"] != "") && ((*map)["TOOLBAR1"].toInt() == 0) )
		{
			btb1 = FALSE;
		}

		if ( ((*map)["TOOLBAR2"] != "") && ((*map)["TOOLBAR2"].toInt() == 0) )
		{
			btb2 = FALSE;
		}

		// restore active page
		TabWidget_SERVERLIST->setCurrentPage((*map)["ACTIVEPAGE"].toInt());
		// restore linedit
		LineEdit_SERVER->setText((*map)["LE_SERVER"]);
	}

	SetToolBar( Frame_TOOLBAR1_HIDE, Frame_TOOLBAR1_SHOW, btb1 );
	SetToolBar( Frame_TOOLBAR2_HIDE, Frame_TOOLBAR2_SHOW, btb2 );

	connect( LineEdit_SERVER, SIGNAL(returnPressed()), this, SLOT(slotConnect()) );
	connect( LineEdit_SERVER, SIGNAL(returnPressed()), this, SLOT(slotConnect()) );
	connect( ToolButton_RELOADPUBLICHUBLIST, SIGNAL(clicked()), this, SLOT(slotReloadPublicHubList()) );
	connect( ToolButton_UPDATEPUBLICHUBLIST, SIGNAL(clicked()), this, SLOT(slotUpdatePublicHubList()) );
	connect( ToolButton_CONNECT, SIGNAL(clicked()), this, SLOT(slotConnect()) );

	// public list
	connect( ListView_PUBLIC,SIGNAL(doubleClicked(QListViewItem*, const QPoint &, int)), this, SLOT(slotDoubleClicked(QListViewItem*, const QPoint &, int)) );
	connect( ListView_PUBLIC,SIGNAL(returnPressed(QListViewItem*)), this, SLOT(slotReturnPressed(QListViewItem*)) );
	connect( ListView_PUBLIC,SIGNAL(contextMenuRequested( QListViewItem *, const QPoint &, int )), this, SLOT(slotRightButtonClickedPublicList(QListViewItem*, const QPoint &, int )) );

	// bookmark list
	connect( ListView_BOOKMARKS,SIGNAL(doubleClicked(QListViewItem*, const QPoint &, int)), this, SLOT(slotDoubleClicked(QListViewItem*, const QPoint &, int)) );
	connect( ListView_BOOKMARKS,SIGNAL(returnPressed(QListViewItem*)), this, SLOT(slotReturnPressed(QListViewItem*)) );
	connect( ListView_BOOKMARKS,SIGNAL(contextMenuRequested( QListViewItem *, const QPoint &, int )), this, SLOT(slotRightButtonClickedBookmarkList(QListViewItem*, const QPoint &, int )) );

	connect( TabWidget_SERVERLIST,SIGNAL(currentChanged(QWidget*)), this, SLOT(slotTabWidgetCurrentChange(QWidget*)) );

	// filter
	connect( ToolButton_ADDFILTER, SIGNAL(clicked()), this, SLOT(slotAddFilter()) );
	connect( ToolButton_EDITFILTER, SIGNAL(clicked()), this, SLOT(slotEditFilter()) );
	connect( ToolButton_DELFILTER, SIGNAL(clicked()), this, SLOT(slotDelFilter()) );
	connect( ComboBox_FILTER, SIGNAL(activated( const QString & )), this, SLOT(slotFilterChange( const QString &)) );

	connect( &m_Timer, SIGNAL(timeout()), this, SLOT(timerDone()) );

	// load filter
	g_pConfig->LoadDCHubFilter(&m_HubFilterList);

	// create default
	if ( m_HubFilterList.Count() == 0 )
	{
		HubFilterObject = new DC_HubFilterObject();

		HubFilterObject->m_sFilterName = "Default";

		m_HubFilterList.Add( HubFilterObject->m_sFilterName, HubFilterObject );

		g_pConfig->SaveDCHubFilter(&m_HubFilterList);
	}

	HubFilterObject = 0;

	while ( m_HubFilterList.Next( (CObject*&)HubFilterObject) == 1 )
	{
		ComboBox_FILTER->insertItem( HubFilterObject->m_sFilterName.Data() );

		if ( (*map)["FILTER"] == HubFilterObject->m_sFilterName.Data() )
		{
			bfilter = TRUE;
		}
	}

	// restore filter
	if ( bfilter )
	{
		ComboBox_FILTER->setCurrentText((*map)["FILTER"]);
	}
	else
	{
		ComboBox_FILTER->setCurrentText("Default");
	}

	ShowBookmarkList();
	ShowPublicHubList();

	m_Timer.start( 500, TRUE );
}

/** */
void DCHubListManager::DeInitDocument()
{
	StringMap * map;

	// save hub view settings
	g_pConfig->GetMap("HUBVIEW",map);

	(*map)["X"]          = QString().setNum(parentWidget()->x());
	(*map)["Y"]          = QString().setNum(parentWidget()->y());
	(*map)["WIDTH"]      = QString().setNum(width());
	(*map)["HEIGHT"]     = QString().setNum(height());
	(*map)["VISIBLE"]    = QString().setNum(isVisible());
	(*map)["MAXIMIZED"]  = QString().setNum(isMaximized());
	(*map)["MINIMIZED"]  = QString().setNum(isMinimized());
	(*map)["ENABLED"]    = QString().setNum(isEnabled());
	(*map)["ACTIVEPAGE"] = QString().setNum(TabWidget_SERVERLIST->currentPageIndex());
	(*map)["LE_SERVER"]  = LineEdit_SERVER->text();
	(*map)["FILTER"]     = ComboBox_FILTER->currentText();

	if ( !isEnabled() )
	{
		setEnabled(TRUE);
	}

	(*map)["TOOLBAR1"]  = QString().setNum(Frame_TOOLBAR1_SHOW->isEnabled());
	(*map)["TOOLBAR2"]  = QString().setNum(Frame_TOOLBAR2_SHOW->isEnabled());
}

/** event filter */
bool DCHubListManager::eventFilter(QObject* object, QEvent* event)
{
	if ( event->type() == QEvent::MouseButtonDblClick )
	{
		if ( object == Frame_TOOLBAR1_HIDE )
		{
			SetToolBar( Frame_TOOLBAR1_HIDE, Frame_TOOLBAR1_SHOW, TRUE );
		}
		else if ( object == Frame_TOOLBAR1_SHOW )
		{
			SetToolBar( Frame_TOOLBAR1_HIDE, Frame_TOOLBAR1_SHOW, FALSE );
		}
		else if ( object == Frame_TOOLBAR2_HIDE )
		{
			SetToolBar( Frame_TOOLBAR2_HIDE, Frame_TOOLBAR2_SHOW, TRUE );

			// show progressbar
			if ( m_pHubListUrl != 0 )
				ProgressBar_LOADHUBLIST->show();
		}
		else if ( object == Frame_TOOLBAR2_SHOW )
		{
			SetToolBar( Frame_TOOLBAR2_HIDE, Frame_TOOLBAR2_SHOW, FALSE );
		}
	}

	return QWidget::eventFilter( object, event );    // standard event processing
}

/** callback function */
int DCHubListManager::DC_CallBack( CObject * Object )
{
	int err;

	m_HLMThread.Lock();

	if ( Object != NULL )
	{
		if ( m_pMessageList != NULL )
		{
			m_pMessageList->Add(Object);
			err = 0;
		}
		else
		{
			err = -1;
		}
	}
	else
	{
		err = -1;
	}

	m_HLMThread.UnLock();

	return err;
}

/** */
void DCHubListManager::timerDone()
{
	CObject * Object;
	CDCMessage *DCMsg;
	int i;

	for(i=0;i<50;i++)
	{
		if ( m_HLMThread.TryLock() == FALSE )
		{
			break;
		}

		if ( m_pMessageList != 0 )
		{
			Object = m_pMessageList->Next(0);

			if ( Object != 0 )
			{
				m_pMessageList->Remove(Object);
			}
		}
		else
		{
			Object = 0;
		}

		m_HLMThread.UnLock();

		if ( Object == 0 )
		{
			break;
		}

		DCMsg = (CDCMessage*) Object;

		switch ( DCMsg->m_eType )
		{
			case DC_MESSAGE_GETHUBLIST:
			{
				DCMessageGetHubList * msg = (DCMessageGetHubList*) Object;

				if ( msg->m_bRun == FALSE )
				{
					// enable buttons
					ToolButton_RELOADPUBLICHUBLIST->setEnabled(TRUE);
					ToolButton_UPDATEPUBLICHUBLIST->setEnabled(TRUE);

					// hide progressbar
					ProgressBar_LOADHUBLIST->hide();

					ShowPublicHubList();
				}
				else
				{
					// disable buttons
					ToolButton_RELOADPUBLICHUBLIST->setEnabled(FALSE);
					ToolButton_UPDATEPUBLICHUBLIST->setEnabled(FALSE);

					// show progressbar
					ProgressBar_LOADHUBLIST->show();
				}

				break;
			}

			case DC_MESSAGE_TRANSFER:
			{
				CMessageTransfer *msg = (CMessageTransfer*)Object;

				ProgressBar_LOADHUBLIST->setTotalSteps(msg->m_nLength);
				ProgressBar_LOADHUBLIST->setProgress(msg->m_nTransfered);

				break;
			}

			default:
			{
				break;
			}
		}

		if ( Object )
		{
			delete Object;
		}
	}

	m_Timer.start( 500, TRUE );
}

/** */
void DCHubListManager::ShowPublicHubList()
{
	DCConfigHubItem * hubitem;
	CList<DCConfigHubItem> PublicHubList;
	unsigned int minuser;
	DC_HubFilterObject * HubFilterObject = 0;
	CString s;
	bool bshow;
	DC_QListViewItem *item;
	QString AllFields,Pattern,Contains;
	int i,x=0;

	// disable filter combo box
	ComboBox_FILTER->setEnabled(FALSE);

	TabWidget_SERVERLIST->setTabLabel( TabWidget_SERVERLIST->page(0), tr("Public")+" (0/0)" );

	ListView_PUBLIC->setUpdatesEnabled(FALSE);
	ListView_PUBLIC->clear();

	g_pConfig->GetPublicHubList(&PublicHubList);

	hubitem     = 0;
	minuser     = 0;
	
	// get the hubfilter
	s = ComboBox_FILTER->currentText().ascii();

	if ( s != "" )
	{
		m_HubFilterList.Get( s, (CObject *&)HubFilterObject );

		if ( HubFilterObject &&
		     !HubFilterObject->m_bName &&
		     !HubFilterObject->m_bServer &&
		     !HubFilterObject->m_bDescription &&
		     (HubFilterObject->m_nUser==0) )
		{
			HubFilterObject = 0;
		}
	}

	while( (hubitem=PublicHubList.Next(hubitem)) != 0 )
	{
		bshow = TRUE;

		x++;

		if ( x == 100 )
		{
			qApp->processEvents();
			x = 0;
		}

		// use the filter
		if ( HubFilterObject )
		{
			if ( hubitem->m_sUserCount.asULL() < HubFilterObject->m_nUser )
			{
				bshow = FALSE;
			}
			else
			{
				AllFields = QString::null;

				if ( HubFilterObject->m_bName )
					AllFields += hubitem->m_sName.Data();
				if ( HubFilterObject->m_bServer )
					AllFields += hubitem->m_sHost.Data();
				if ( HubFilterObject->m_bDescription )
					AllFields += hubitem->m_sDescription.Data();

				Contains = HubFilterObject->m_sContains.Data();

				if ( AllFields != Contains )
				{
					i = 0;
					while ( !(Pattern=Contains.section(" ",i,i,QString::SectionSkipEmpty)).isEmpty())
					{
						i++;
						if ( AllFields.contains(Pattern,FALSE) == 0 )
						{
							bshow = FALSE;
							break;
						}
					}
				}
			}
		}

		if ( bshow )
		{
			item = new DC_QListViewItem(ListView_PUBLIC);

			item->myvalue = hubitem->m_sUserCount.asULL();
			item->mycol = 3;

			item->setText(0,QString::fromUtf8(hubitem->m_sName.Data()));
			item->setText(1,QString::fromUtf8(hubitem->m_sHost.Data()));
			item->setText(2,QString::fromUtf8(hubitem->m_sDescription.Data()));
			item->setText(3,hubitem->m_sUserCount.Data());
		}
	}

	ListView_PUBLIC->setUpdatesEnabled(TRUE);
	ListView_PUBLIC->triggerUpdate();

	TabWidget_SERVERLIST->setTabLabel( TabWidget_SERVERLIST->page(0), tr("Public")+" ("+QString().setNum(ListView_PUBLIC->childCount())+"/"+QString().setNum(PublicHubList.Count())+")");

	// enable filter combo box
	ComboBox_FILTER->setEnabled(TRUE);
}

/** */
void DCHubListManager::ShowBookmarkList()
{
	int x = 0;
	DCConfigHubItem * hubitem = 0;
	CList<DCConfigHubItem> list;
	DCConfigHubProfile ConfigHubProfile;

	g_pConfig->GetBookmarkHubList(&list);

	ListView_BOOKMARKS->setUpdatesEnabled(FALSE);
	ListView_BOOKMARKS->clear();

	while( (hubitem=list.Next(hubitem)) != 0 )
	{
		new QListViewItem(ListView_BOOKMARKS,hubitem->m_sName.Data(),hubitem->m_sHost.Data(),hubitem->m_sDescription.Data());

		x++;

		if ( x == 100 )
		{
			qApp->processEvents();
			x = 0;
		}
	}

	ListView_BOOKMARKS->setUpdatesEnabled(TRUE);
	ListView_BOOKMARKS->triggerUpdate();

	TabWidget_SERVERLIST->setTabLabel( TabWidget_SERVERLIST->page(1), tr("Bookmarks")+" ("+QString().setNum(ListView_BOOKMARKS->childCount())+")" );
}

/** */
void DCHubListManager::slotReloadPublicHubList()
{
	g_pConfig->ClearPublicHubList();

	GetPublicHubList();
}

/** update public hub list */
void DCHubListManager::slotUpdatePublicHubList()
{
	GetPublicHubList();
}

/** */
void DCHubListManager::slotDoubleClicked( QListViewItem * item, const QPoint &, int )
{
	if ( item )
		g_pConnectionManager->Connect( item->text(0).ascii(), item->text(1).ascii() );
}

/** */
void DCHubListManager::slotReturnPressed( QListViewItem * item )
{
	if ( item )
		g_pConnectionManager->Connect( item->text(0).ascii(), item->text(1).ascii() );
}

/** */
void DCHubListManager::slotConnect()
{
	g_pConnectionManager->Connect( "", LineEdit_SERVER->text().ascii() );
}

/** */
void DCHubListManager::slotAddFilter()
{
	CString s;
	DC_HubFilterObject * HubFilterObject, * HubFilterObject1 ;
	DCHubFilter * hf;

	hf = new DCHubFilter(this);

	if ( hf->exec() == QDialog::Accepted )
	{
		HubFilterObject = new  DC_HubFilterObject();

		// get the new data
		hf->Get( HubFilterObject );

		if ( HubFilterObject->m_sFilterName == "" )
		{
			// todo: error message

			delete HubFilterObject;
		}
		else if ( m_HubFilterList.Get( HubFilterObject->m_sFilterName, (CObject *&)HubFilterObject1 ) == 0 )
		{
			// todo: error message already exist

			delete HubFilterObject;
		}
		else
		{
			m_HubFilterList.Add( HubFilterObject->m_sFilterName, HubFilterObject );

			ComboBox_FILTER->insertItem( HubFilterObject->m_sFilterName.Data() );
		}

		g_pConfig->SaveDCHubFilter(&m_HubFilterList);

		delete hf;
	}
}

/** */
void DCHubListManager::slotEditFilter()
{
	CString s;
	DC_HubFilterObject * HubFilterObject, * HubFilterObject1;
	DCHubFilter * hf;

	s = ComboBox_FILTER->currentText().ascii();

	if ( (s != "") && (s != "Default") )
	{
		if ( m_HubFilterList.Get( s, (CObject *&)HubFilterObject ) == 0 )
		{
			hf = new DCHubFilter(this);

			hf->Edit( HubFilterObject );

			if ( hf->exec() == QDialog::Accepted )
			{
				// get the new data
				hf->Get( HubFilterObject );

				if ( HubFilterObject->m_sFilterName == "" )
				{
					HubFilterObject->m_sFilterName = s;

					// todo: error message
				}
				else if ( s != HubFilterObject->m_sFilterName )
				{
					if ( m_HubFilterList.Get( HubFilterObject->m_sFilterName, (CObject *&)HubFilterObject1 ) == 0 )
					{
						// todo: error message already exist
					}
					else
					{
						m_HubFilterList.Remove(s);
						m_HubFilterList.Add( HubFilterObject->m_sFilterName, HubFilterObject );

						ComboBox_FILTER->changeItem( HubFilterObject->m_sFilterName.Data(), ComboBox_FILTER->currentItem() );
					}
				}

				// update view
				slotFilterChange( HubFilterObject->m_sFilterName.Data() );

				g_pConfig->SaveDCHubFilter(&m_HubFilterList);
			}

			delete hf;
		}
	}
}

/** */
void DCHubListManager::slotDelFilter()
{
	CString s;

	s = ComboBox_FILTER->currentText().ascii();

	if ( (s != "") && (s != "Default") )
	{
		ComboBox_FILTER->removeItem(ComboBox_FILTER->currentItem());

		m_HubFilterList.Del(s);

		g_pConfig->SaveDCHubFilter(&m_HubFilterList);
	}
}

/** */
void DCHubListManager::slotFilterChange( const QString & s )
{
	if ( s != "" )
	{
		ShowPublicHubList();
	}
}

/** */
void DCHubListManager::RemoveBookmark( QListViewItem * item )
{
	if ( g_pConfig->RemoveBookmarkHub( item->text(0).ascii(), item->text(1).ascii(), item->text(2).ascii() ) == TRUE )
	{
		g_pConfig->SaveDCBookHub();

		ListView_BOOKMARKS->takeItem(item);
		delete item;

		// update tabbar
		TabWidget_SERVERLIST->setTabLabel( TabWidget_SERVERLIST->page(1), tr("Bookmarks")+" ("+QString().setNum(ListView_BOOKMARKS->childCount())+")" );
	}
}

/** */
void DCHubListManager::AddBookmark( QString hubname, QString hubhost, QString description )
{
	if ( g_pConfig->AddBookmarkHub( hubname.ascii(), hubhost.ascii(), description.ascii() ) == TRUE )
	{
		g_pConfig->SaveDCBookHub();

		new QListViewItem( ListView_BOOKMARKS, hubname, hubhost, description );

		// update tabbar
		TabWidget_SERVERLIST->setTabLabel( TabWidget_SERVERLIST->page(1), tr("Bookmarks")+" ("+QString().setNum(ListView_BOOKMARKS->childCount())+")" );
	}
}

/** */
void DCHubListManager::UpdateBookmark( QString hubname, QString hubhost, QString description )
{
	if ( g_pConfig->UpdateBookmarkHub( hubname.ascii(), hubhost.ascii(), description.ascii() ) == TRUE )
	{
		g_pConfig->SaveDCBookHub();
	}
}

/** */
CStringList * DCHubListManager::GetFilteredHubList()
{
	CStringList * list = 0;
	DCConfigHubItem * hubitem;
	CObject * object;
	QListViewItemIterator it( ListView_PUBLIC );

	hubitem = 0;
	list = new CStringList();

	for ( ; it.current(); it++ )
	{
		if ( it.current()->isEnabled() )
		{
			if ( list->Get( it.current()->text(1).ascii(), (CObject *&)object ) != 0 )
			{
				list->Add(it.current()->text(1).ascii(), new CString(it.current()->text(1).ascii()));
			}
		}
	}

	if ( list->Count() == 0 )
	{
		delete list;
		list = 0;
	}

	return list;
}

/** */
void DCHubListManager::slotRightButtonClickedBookmarkList( QListViewItem * /*item*/, const QPoint &, int )
{
	int id;
	QPopupMenu *m;
	DCEditServer * des;
	QPtrList<QListViewItem> selitems;
	QListViewItem * curitem;
	DCConfigHubProfile pConfigHubProfile;
	DCConfigHubItem ConfigHubItem;

	CString profilename;

	selectedItems(ListView_BOOKMARKS,selitems);

	m = new QPopupMenu(this);

	DCMenuHandler::InsertMenu( m, emiCONNECT, (selitems.count() > 0) );
	DCMenuHandler::InsertMenu( m, emiSEPARATOR );
	DCMenuHandler::InsertMenu( m, emiADD );
	DCMenuHandler::InsertMenu( m, emiEDIT, (selitems.count() == 1) );
	DCMenuHandler::InsertMenu( m, emiREMOVE, (selitems.count() > 0) );
	DCMenuHandler::InsertMenu( m, emiSEPARATOR );
	DCMenuHandler::InsertMenu( m, emiUPDATE_SERVER, (selitems.count() > 0) );
	DCMenuHandler::InsertMenu( m, emiUPDATE_ALL_SERVER );
	DCMenuHandler::InsertMenu( m, emiSEPARATOR );
	DCMenuHandler::InsertMenu( m, emiHUB_PROFILE_EDITOR );

	id = m->exec(QCursor::pos());

	delete m;

	if ( id == -1 )
	{
		return;
	}

	if ( id == emiADD )
	{
		des = new DCEditServer();
		des->setCaption(tr("Add Bookmark"));

		//reset values
		des->Reset();
		
		while ( des->exec() == QDialog::Accepted )
		{
			// first we check some settings
			if ( des->LineEdit_NAME->text() == "" )
			{
				QMessageBox::critical( this, tr("Error"), tr("Please enter a hubname.") );

				continue;
			}

			if ( des->LineEdit_HOST->text() == "" )
			{
				QMessageBox::critical( this, tr("Error"), tr("Please enter a hubhost.") );

				continue;
			}

			// add bookmark to the list
			AddBookmark( des->LineEdit_NAME->text(), des->LineEdit_HOST->text(), des->LineEdit_DESCRIPTION->text() );

			// check if profiling possible
			if ( des->CheckBox_PROFILE->isChecked() == TRUE )
			{
				// get profile from dialog
				des->GetProfile(&pConfigHubProfile);
				
				// add new profile
				g_pConfig->AddHubProfile( &pConfigHubProfile );

				// save profile
				g_pConfig->SaveHubProfile();

				// set bookmark for that hub
				g_pConfig->SetBookmarkHubProfile(des->LineEdit_NAME->text().ascii(),des->LineEdit_NAME->text().ascii());
			}
			else
			{
				// clear bookmark from that hub
				g_pConfig->SetBookmarkHubProfile(des->LineEdit_NAME->text().ascii(),"");
			}
			
			// update myinfo
			g_pConnectionManager->SendMyInfoToConnectedServers();
			
			break;
		}

		delete des;
	}
	else if ( id == emiEDIT )
	{
		bool prof = FALSE;

		// edit only for one selected item
		curitem = selitems.first();

		des = new DCEditServer();
		des->setCaption(tr("Edit Bookmark"));

		des->LineEdit_NAME->setText(curitem->text(0));
		des->LineEdit_HOST->setText(curitem->text(1));
		des->LineEdit_DESCRIPTION->setText(curitem->text(2));

		// hubitem
		if ( g_pConfig->GetBookmarkHub( curitem->text(0).ascii(), &ConfigHubItem ) == TRUE )
		{
			if ( ConfigHubItem.m_sProfile != "" )
			{
				// get profile
				if ( g_pConfig->GetHubProfile( ConfigHubItem.m_sProfile, &pConfigHubProfile ) == TRUE )
				{
					des->SetProfile(&pConfigHubProfile);

					prof = TRUE;
				}
			}
		}

		while ( des->exec() == QDialog::Accepted  )
		{
			// first we check some settings
			if ( des->LineEdit_NAME->text() == "" )
			{
				QMessageBox::critical( this, tr("Error"), tr("Please enter a hubname.") );

				continue;
			}

			if ( des->LineEdit_HOST->text() == "" )
			{
				QMessageBox::critical( this, tr("Error"), tr("Please enter a hubhost.") );

				continue;
			}

			RemoveBookmark( curitem );

			if ( prof == TRUE )
			{
				// remove the profile
				g_pConfig->DelHubProfile( pConfigHubProfile.m_sName );
                	}

			// add as new bookmark
			AddBookmark( des->LineEdit_NAME->text(), des->LineEdit_HOST->text(), des->LineEdit_DESCRIPTION->text() );

			// check if profiling possible
			if ( des->CheckBox_PROFILE->isChecked() == TRUE )
			{
				// get profile from dialog
				des->GetProfile(&pConfigHubProfile);

				// add new profile
				g_pConfig->AddHubProfile( &pConfigHubProfile );

				// save profile
				g_pConfig->SaveHubProfile();

				// set bookmark for that hub
				g_pConfig->SetBookmarkHubProfile(des->LineEdit_NAME->text().ascii(),des->LineEdit_NAME->text().ascii());
			}
			else
			{
				// remove bookmark from that hub
				g_pConfig->SetBookmarkHubProfile(des->LineEdit_NAME->text().ascii(),"");
			}

			// update myinfo
			g_pConnectionManager->SendMyInfoToConnectedServers();

			break;
		}

		delete des;
	}
	else if ( id == emiREMOVE )
	{
		int i;
		StringMap * map;

		if ( g_pConfig->GetMap("DIALOG_REMOVE_BOOKMARK",map) == FALSE )
		{
			(*map)["SHOW"]    = QString().setNum(1);
			(*map)["DEFAULT"] = QString().setNum(0);
		}

		if ( ((*map)["SHOW"].toInt() == 1) || ((*map)["DEFAULT"].toInt() == 1) )
		{
			CDialogMessage * dlg = new CDialogMessage( this,
				QMessageBox::Warning,
				tr("Remove bookmarks"),
        			tr("You are sure ?"),
				tr("Remove"),
				tr("Cancel") );

			i = dlg->exec();

			(*map)["SHOW"]    = QString().setNum(!dlg->GetCheckBoxStatus());
			(*map)["DEFAULT"] = QString().setNum(i);

			delete dlg;


		}
		else
		{
			i = (*map)["DEFAULT"].toInt();
		}

		switch(i)
		{
	    		case 1: // The user clicked the cancel
        			return;
			default:
				break;
		}

	        for ( curitem = selitems.first(); curitem; curitem = selitems.next() )
	        {
			// remove profile for that entry
			if ( g_pConfig->GetHubProfile( curitem->text(0).ascii(), &pConfigHubProfile ) == TRUE )
			{
				g_pConfig->DelHubProfile( pConfigHubProfile.m_sName );
			}

			// remove bookmark
			RemoveBookmark(curitem);
		}
		
		// save changes to profile list, some may have been deleted
		g_pConfig->SaveHubProfile();
		
		// update myinfo
		g_pConnectionManager->SendMyInfoToConnectedServers();
	}
	else if ( id == emiCONNECT )
	{
	        for ( curitem = selitems.first(); curitem; curitem = selitems.next() )
	        {
			g_pConnectionManager->Connect( curitem->text(0).ascii(), curitem->text(1).ascii() );
		}
	}
	else if ( id == emiUPDATE_SERVER )
	{
		DCConfigHubItem hubitem;

	        for ( curitem = selitems.first(); curitem; curitem = selitems.next() )
	        {
			if ( g_pConfig->GetPublicHub( curitem->text(0).ascii(), &hubitem ) == TRUE )
			{
				UpdateBookmark( hubitem.m_sName.Data(), hubitem.m_sHost.Data(), hubitem.m_sDescription.Data() );
				curitem->setText(1,hubitem.m_sHost.Data());
				curitem->setText(2,hubitem.m_sDescription.Data());
			}
		}
	}
	else if ( id == emiUPDATE_ALL_SERVER )
	{
		DCConfigHubItem * hubitem = 0;
		DCConfigHubItem hubitem1;
		CList<DCConfigHubItem> list;

		g_pConfig->GetBookmarkHubList(&list);

		while( (hubitem=list.Next(hubitem)) != 0 )
		{
			if ( g_pConfig->GetPublicHub( hubitem->m_sName, &hubitem1 ) == TRUE )
			{
				g_pConfig->UpdateBookmarkHub( hubitem1.m_sName, hubitem1.m_sHost, hubitem1.m_sDescription );
			}
		}

		g_pConfig->SaveDCBookHub();

		ShowBookmarkList();
	}
	else if ( id == emiHUB_PROFILE_EDITOR )
	{
		DCHubProfile * dlg = new DCHubProfile();

		dlg->exec();

		delete dlg;
		
		// update myinfo
		g_pConnectionManager->SendMyInfoToConnectedServers();
	}
}

/** */
void DCHubListManager::slotRightButtonClickedPublicList( QListViewItem * /*item*/, const QPoint &, int column )
{
	int id;
	QPopupMenu *m;
	QPtrList<QListViewItem> selitems;
	QListViewItem * curitem;
	int numSelected;
	
	numSelected = selectedItems(ListView_PUBLIC,selitems);
	
	if ( numSelected == 0 )
	{
		return;
	}

	m = new QPopupMenu(this);

	DCMenuHandler::InsertMenu( m, emiCONNECT );
	DCMenuHandler::InsertMenu( m, emiSEPARATOR );
	DCMenuHandler::InsertMenu( m, emiADD_BOOKMARK );
	DCMenuHandler::InsertMenu( m, emiSEPARATOR );
	DCMenuHandler::InsertMenu( m, emiCOPY_COLUMN_TO_CLIPBOARD, (numSelected == 1) );
	DCMenuHandler::InsertMenu( m, emiCOPY_ROW_TO_CLIPBOARD, (numSelected == 1) );

	id = m->exec(QCursor::pos());

	delete m;

	if ( id == -1 )
	{
		return;
	}

	if ( id == emiCONNECT )
	{
	        for ( curitem = selitems.first(); curitem; curitem = selitems.next() )
	        {
			g_pConnectionManager->Connect( curitem->text(0).ascii(), curitem->text(1).ascii() );
		}
	}
	else if ( id == emiADD_BOOKMARK )
	{
	        for ( curitem = selitems.first(); curitem; curitem = selitems.next() )
	        {
			AddBookmark( curitem->text(0), curitem->text(1), curitem->text(2) );
		}

		TabWidget_SERVERLIST->setTabLabel( TabWidget_SERVERLIST->page(1), tr("Bookmarks")+" ("+QString().setNum(ListView_BOOKMARKS->childCount())+")" );
	}
	else if ( id == emiCOPY_COLUMN_TO_CLIPBOARD )
	{
		QClipboard *cb = QApplication::clipboard();
		cb->setText("");

		curitem = selitems.first();
		cb->setText( curitem->text(column) );
	}
	else if ( id == emiCOPY_ROW_TO_CLIPBOARD )
	{
		int idx;
		QString s="";
		QClipboard *cb = QApplication::clipboard();
		cb->setText("");

		curitem = selitems.first();
		
		for( idx = 0; idx < ListView_PUBLIC->columns(); idx++ )
		{
			s += curitem->text(idx) + "\n";
		}
		cb->setText(s);
	}
}
