/*********************************************************************************
* C++ Implementation: kbearquickconnectdlg.cpp
* Description:
*                              
* Begin : tis feb 04 2003
* Author : Björn Sahlström <kbjorn@users.sourceforge.net> (C) 2003
* Copyright : See COPYING file that comes with this distribution
**********************************************************************************/

//////////////////////////////////////////////////////////////////////
// Qt specific include files
#include <qcheckbox.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qstringlist.h>
//////////////////////////////////////////////////////////////////////
// KDE specific include files
#include <kcombobox.h>
#include <klineedit.h>
#include <knuminput.h>
#include <klocale.h>
#include <kpassdlg.h>
#include <kurl.h>
#include <kapplication.h>
#include <kpassdlg.h>
#include <kprotocolinfo.h>
#include <kmessagebox.h>
#include <dcopclient.h>
#include <kdebug.h>
//////////////////////////////////////////////////////////////////////
// System specific include files
#include <netdb.h>
#include <sys/param.h>
#include <netinet/in.h>
#include <string.h>
//////////////////////////////////////////////////////////////////////
// Application specific include files
#include "kbearquickconnectdlg.h"
#include "misc.h"

#include "kbearquickconnectdlg.moc"

using namespace KBear;
//-----------------------------------------------
KBearQuickConnectDlg::KBearQuickConnectDlg(QWidget *parent, const char *name)
	:	QDialog(parent, name), m_hasKBearFTP( false )
{
	setupGUI();
}
//-----------------------------------------------
KBearQuickConnectDlg::~KBearQuickConnectDlg() {
}
//-----------------------------------------------
void KBearQuickConnectDlg::accept() {
	SiteInfo info;
	if( m_protocolComboBox->currentText() == "ftp" && m_hasKBearFTP )
		info.setProtocol( "kbearftp" );
	else
		info.setProtocol( m_protocolComboBox->currentText() );
	
	info.setLabel( m_hostNameEdit->text() ); // we use the host name as label
	info.setAnonym( m_anonymousCheck->isChecked() );
	info.setHost( m_hostNameEdit->text() );
	info.setPort( m_portSpinBox->value() );
	info.setUser( m_userNameEdit->text() );
	info.setPass( m_passwordEdit->text() );
	info.setRemotePath( m_remoteDirEdit->text() );

	KURL url = info.url();
	if( ! url.hasHost() ) {
		KMessageBox::error ( this, i18n("You must set a host !"));
		return;
	}

	if( ! url.isValid() || url.isMalformed() ) {
		KMessageBox::error ( this, i18n("Invalid URL:\n%1\n\nPlease try again.").arg(url.prettyURL()));
		return;
	}
	
	if( m_saveToSiteManagerCheckBox->isChecked() ) {
		QString pass = KBear::encodePassword( info.pass() );
		info.setPass( pass );
		QByteArray data;
		QDataStream arg( data, IO_WriteOnly );
		arg << info;
		if( ! kapp->dcopClient()->send("kbearsitemanagerdb", "SiteManagerDBInterface", "saveSite(SiteInfo)", data ) )
			kdDebug()<<"DCOP call saveSite(SiteInfo)  to kbearsitemanagerdb failed !!!!"<<endl;
	}
	emit openSite( info );
	QDialog::accept();
}
//-----------------------------------------------
void KBearQuickConnectDlg::slotURLChanged( const QString& str ) {
	m_hostNameEdit->blockSignals( true );
	m_userNameEdit->blockSignals( true );
	m_passwordEdit->blockSignals( true );
	m_remoteDirEdit->blockSignals( true );
	m_portSpinBox->blockSignals( true );
	m_anonymousCheck->blockSignals( true );
	m_protocolComboBox->blockSignals( true );
	
	KURL tmpURL = str;
	if( ! tmpURL.protocol().isEmpty() )
		m_url.setProtocol( tmpURL.protocol() );
	if( tmpURL.hasHost() )
		m_url.setHost( tmpURL.host() );
	if( tmpURL.port() > 0 )
		m_url.setPort( tmpURL.port() );
	if( tmpURL.hasUser() )
		m_url.setUser( tmpURL.user() );
	if( tmpURL.hasPass() )
		m_url.setPass( tmpURL.pass() );
	if( ! tmpURL.path().isEmpty() )
		m_url.setPath( tmpURL.path() );
	
	m_hostNameEdit->setText( m_url.host() );
	m_portSpinBox->setValue( m_url.port() );
	if( m_protocolComboBox->contains( m_url.protocol() ) ) {
		m_protocolComboBox->setCurrentItem( m_url.protocol() );
/*
		int port = getPortForProtocol( m_url.protocol() );
		if( port > 0 && m_url.port() == 0 ) {
			m_portSpinBox->setValue( port );
			m_url.setPort( port );
		}
*/
	}
	m_userNameEdit->setText( m_url.user() );
//	m_anonymousCheck->setChecked( ! m_url.hasUser() );
	m_passwordEdit->setText( m_url.pass() );
	m_remoteDirEdit->setText( m_url.path() );
//	m_urlEdit->setText( m_url.prettyURL() );
	m_hostNameEdit->blockSignals( false );
	m_userNameEdit->blockSignals( false );
	m_passwordEdit->blockSignals( false );
	m_remoteDirEdit->blockSignals( false );
	m_portSpinBox->blockSignals( false );
	m_anonymousCheck->blockSignals( false );
	m_protocolComboBox->blockSignals( false );
}
//-----------------------------------------------
void KBearQuickConnectDlg::slotSelectedProtocol( const QString& protocol ){
	int port = getPortForProtocol( protocol );
	if( port > 0 ) {
		m_portSpinBox->setValue( port );
		m_url.setPort( port );
	}
	m_url.setProtocol( protocol );
	m_urlEdit->setText( m_url.prettyURL() );
}
//-----------------------------------------------
void KBearQuickConnectDlg::slotChanged() {
 	m_url.setHost( m_hostNameEdit->text() );
	m_url.setPort( m_portSpinBox->value() );
	m_url.setUser( m_userNameEdit->text() );
	m_url.setPass( m_passwordEdit->text() );
	m_url.setPath( m_remoteDirEdit->text() );
	m_urlEdit->setText( m_url.prettyURL() );
}
//-----------------------------------------------
void KBearQuickConnectDlg::slotSetAnonymous( bool b ) {
	if( b ) {
		m_userNameEdit->setText( QString::fromLatin1("anonymous") );
		m_passwordEdit->setText( QString::fromLatin1("anonymous@") );
		m_remoteDirEdit->setFocus();
		m_url.setUser( m_userNameEdit->text() );
		m_url.setPass( m_passwordEdit->text() );
		m_urlEdit->setText( m_url.prettyURL() );
	}
	else {
		m_userNameEdit->setText("");
		m_passwordEdit->setText("");
		m_userNameEdit->setFocus();
		m_url.setUser( m_userNameEdit->text() );
		m_url.setPass( m_passwordEdit->text() );
		m_urlEdit->setText( m_url.prettyURL() );
	}
}
//-----------------------------------------------
void KBearQuickConnectDlg::setupGUI() {
	setMinimumWidth( 350 );
	setCaption( i18n( "Quick Connect" ) );
	setFocusPolicy( QDialog::WheelFocus );
	setSizeGripEnabled( TRUE );
	QGridLayout* mainLayout = new QGridLayout( this, 1, 1, 11, 6, "mainLayout"); 

	QLabel* URLLabel = new QLabel( "URL:", this, "URLLabel" );
	mainLayout->addMultiCellWidget( URLLabel, 0, 0, 0, 1 );
	m_urlEdit = new KLineEdit( this, "m_urlEdit" );
	m_urlEdit->setURLDropsEnabled( true );
	mainLayout->addMultiCellWidget( m_urlEdit, 1, 1, 0, 1 );
	
	QLabel* hostlabel = new QLabel( this, "hostlabel" );
	hostlabel->setText( i18n( "Hostname:" ) );
	mainLayout->addWidget( hostlabel, 2, 0 );

	m_hostNameEdit = new KLineEdit( this, "m_hostNameEdit" );
	QString tmp = i18n( "Enter URL to remote host here" );
	QToolTip::add( m_hostNameEdit, tmp );
	QWhatsThis::add( m_hostNameEdit, tmp );
	mainLayout->addWidget( m_hostNameEdit, 2, 1 );

	QGridLayout* portLayout = new QGridLayout( 0, 1, 1, 0, 6, "portLayout"); 

	QLabel* portLabel = new QLabel( this, "portLabel" );
	portLabel->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)5, 0, 0, portLabel->sizePolicy().hasHeightForWidth() ) );
	portLabel->setText( i18n( "Port:" ) );

	portLayout->addMultiCellWidget( portLabel, 0, 0, 0, 1 );
	
	QLabel* protocolLabel = new QLabel( this, "protocolLabel" );
	protocolLabel->setText( i18n( "Protocol:" ) );

	portLayout->addWidget( protocolLabel, 0, 2 );

	m_portSpinBox = new KIntSpinBox( this, "m_portSpinBox" );
	m_portSpinBox->setMaxValue( 65535 );
	m_portSpinBox->setMinValue( 0 );
	m_portSpinBox->setValue( 21 );
	QToolTip::add( m_portSpinBox, i18n( "Select port to use here." ) );
	QWhatsThis::add( m_portSpinBox, i18n( "Select port to use here. When you select protocol the port is set automatically to the default port for that protocol according to your system settings. Here you can override this setting." ) );

	portLayout->addWidget( m_portSpinBox, 1, 0 );
	
	QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	portLayout->addItem( spacer, 1, 1 );

	m_protocolComboBox = new KComboBox( FALSE, this, "m_protocolComboBox" );
	m_protocolComboBox->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)0, 1, 0, m_protocolComboBox->sizePolicy().hasHeightForWidth() ) );
	m_protocolComboBox->setAutoCompletion( FALSE );
	m_protocolComboBox->setDuplicatesEnabled( FALSE );
	QToolTip::add( m_protocolComboBox, i18n( "Select protocol to use here." ) );
	QWhatsThis::add( m_protocolComboBox, i18n( "Select protocol to use here.\n"
																							"When you select protocol the port is set automatically to the default port "
																							"for that protocol according to your system settings." ) );

	portLayout->addWidget( m_protocolComboBox, 1, 2 );
	
	mainLayout->addMultiCellLayout( portLayout, 3, 3, 0, 1 );

	m_anonymousCheck = new QCheckBox( this, "m_anonymousCheck" );
	m_anonymousCheck->setText( i18n( "Anonymous Login" ) );
	tmp = i18n( "Check this if you want to use anonymous login" );
	QToolTip::add( m_anonymousCheck, tmp );
	QWhatsThis::add( m_anonymousCheck, tmp );
	mainLayout->addMultiCellWidget( m_anonymousCheck, 4, 4, 0, 1 );
    
	QLabel* userNameLabel = new QLabel( this, "userNameLabel" );
	userNameLabel->setText( i18n( "Username:" ) );
	mainLayout->addWidget( userNameLabel, 5, 0 );

	m_userNameEdit = new KLineEdit( this, "m_userNameEdit" );
	tmp = i18n( "Enter your user name here. If you leave this empty anonymous login is expected!!!" );
	QToolTip::add( m_userNameEdit, tmp );
	QWhatsThis::add( m_userNameEdit, tmp );
	mainLayout->addWidget( m_userNameEdit, 5, 1 );

	QLabel* passwordLabel = new QLabel( this, "passwordLabel" );
	passwordLabel->setText( i18n( "Password:" ) );
	mainLayout->addWidget( passwordLabel, 6, 0 );

	m_passwordEdit = new KLineEdit( this, "m_passwordEdit" );
	m_passwordEdit->setEchoMode( QLineEdit::Password );
	tmp = i18n( "Enter your password here." );
	QToolTip::add( m_passwordEdit, tmp );
	QWhatsThis::add( m_passwordEdit, tmp );
	mainLayout->addWidget( m_passwordEdit, 6, 1 );

	QLabel* remoteDirLabel = new QLabel( this, "remoteDirLabel" );
	remoteDirLabel->setText( i18n( "Default directory:" ) );
	mainLayout->addWidget( remoteDirLabel, 7, 0 );

	m_remoteDirEdit = new KLineEdit( this, "m_remoteDirEdit" );
	tmp = i18n( "Enter start directory on remote host here" );
	QToolTip::add( m_remoteDirEdit, tmp );
	QWhatsThis::add( m_remoteDirEdit, tmp );
	mainLayout->addWidget( m_remoteDirEdit, 7, 1 );
    
	 m_saveToSiteManagerCheckBox = new QCheckBox( this, "m_saveToSiteManagerCheckBox" );
	m_saveToSiteManagerCheckBox->setText( i18n( "Save to Sitemanager" ) );
	tmp = i18n( "Check this if you want this site to be automatically added to the Sitemanager." );
	QToolTip::add( m_saveToSiteManagerCheckBox, tmp );
	QWhatsThis::add( m_saveToSiteManagerCheckBox, tmp );
	mainLayout->addMultiCellWidget( m_saveToSiteManagerCheckBox, 8, 8, 0, 1 );

	QHBoxLayout* buttonLayout = new QHBoxLayout( 0, 0, 6, "buttonLayout"); 
	spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	buttonLayout->addItem( spacer );

	QPushButton* cancelButton = new QPushButton( this, "cancelButton" );
	QFont cancelButton_font(  cancelButton->font() );
	cancelButton_font.setFamily( "adobe-helvetica" );
	cancelButton_font.setPointSize( 18 );
	cancelButton_font.setBold( TRUE );
	cancelButton->setFont( cancelButton_font ); 
	cancelButton->setText( i18n( "C&ancel" ) );
	cancelButton->setAutoDefault( TRUE );
	tmp = i18n( "Press button to cancel and exit dialog" );
	QToolTip::add( cancelButton, tmp );
	QWhatsThis::add( cancelButton, tmp );
	buttonLayout->addWidget( cancelButton );
	spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	buttonLayout->addItem( spacer );

	spacer = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
	mainLayout->addMultiCell( spacer, 9, 9, 0, 1 );
	
	QPushButton* connectButton = new QPushButton( this, "connectButton" );
	QFont connectButton_font(  connectButton->font() );
	connectButton_font.setFamily( "adobe-helvetica" );
	connectButton_font.setPointSize( 18 );
	connectButton_font.setBold( TRUE );
	connectButton->setFont( connectButton_font ); 
	connectButton->setText( i18n( "&Connect" ) );
	connectButton->setAutoDefault( TRUE );
	connectButton->setDefault( TRUE );
	tmp = i18n( "Press button to connect" );
	QToolTip::add( connectButton, tmp );
	QWhatsThis::add( connectButton, tmp );
	buttonLayout->addWidget( connectButton );
	spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	buttonLayout->addItem( spacer );
	
	mainLayout->addMultiCellLayout( buttonLayout, 10, 10, 0, 1 );


	// tab order
	setTabOrder( m_urlEdit, m_hostNameEdit );
	setTabOrder( m_hostNameEdit, m_protocolComboBox );
	setTabOrder( m_protocolComboBox, m_portSpinBox );
	setTabOrder( m_portSpinBox, m_anonymousCheck );
	setTabOrder( m_anonymousCheck, m_userNameEdit );
	setTabOrder( m_userNameEdit, m_passwordEdit );
	setTabOrder( m_passwordEdit, m_remoteDirEdit );
	setTabOrder( m_remoteDirEdit, m_saveToSiteManagerCheckBox );
	setTabOrder( m_saveToSiteManagerCheckBox, cancelButton );
	setTabOrder( cancelButton, connectButton );
	
	bool hasFTP = false;
	QStringList protList = KProtocolInfo::protocols();
	for( QStringList::Iterator it = protList.begin(); it != protList.end(); ++it ) {
		if( ( KProtocolInfo::outputType( *it ) == KProtocolInfo::T_FILESYSTEM )
			&& KProtocolInfo::supportsListing( *it )
			&& KProtocolInfo::supportsReading( *it )
			&& KProtocolInfo::supportsWriting( *it )
			&& KProtocolInfo::supportsMakeDir( *it )
			&& KProtocolInfo::supportsDeleting( *it ) ) {
							
			if( *it == QString::fromLatin1("ftp") )
				hasFTP = true;
			else if( *it == QString::fromLatin1("kbearftp") )
				m_hasKBearFTP = true;
			if( (*it != QString::fromLatin1("floppy")) && (*it != QString::fromLatin1("file")) && ( (*it).left(6) != QString::fromLatin1("webdav")) )
				m_protocolComboBox->insertItem( *it );
			
		}
	}		
	if( hasFTP ) {
		if( m_hasKBearFTP ) {
			m_protocolComboBox->setCurrentText( QString::fromLatin1("kbearftp") );
			m_protocolComboBox->removeItem( m_protocolComboBox->currentItem() );
		}
		m_protocolComboBox->setCurrentText( QString::fromLatin1("ftp") );
		m_url.setProtocol( QString::fromLatin1("ftp") );
	}
	slotSelectedProtocol( m_protocolComboBox->currentText() );
	
	// signals and slots connections
	connect( m_hostNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotChanged() ) );
	connect( m_userNameEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotChanged() ) );
	connect( m_passwordEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotChanged() ) );
	connect( m_remoteDirEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotChanged() ) );
	connect( m_portSpinBox, SIGNAL( valueChanged( int ) ), this, SLOT( slotChanged() ) );
	connect( m_anonymousCheck, SIGNAL( toggled(bool) ), this, SLOT( slotSetAnonymous( bool ) ) );
	connect( m_urlEdit, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotURLChanged( const QString& ) ) );
	connect( connectButton, SIGNAL( clicked() ), this, SLOT( accept() ) );
	connect( cancelButton, SIGNAL( clicked() ), this, SLOT( reject() ) );
	
	connect( m_protocolComboBox, SIGNAL( activated( const QString& )),
					this, SLOT( slotSelectedProtocol( const QString& ) ) );
	m_hostNameEdit->setFocus();

}
//-----------------------------------------------
