/***************************************************************************
                          gftpimportfilterplugin.cpp  -  description
                             -------------------
    begin                : tis mar 19 2002
    copyright            : (C) 2003 by Björn Sahlström
    email                : kbjorn@users.sourceforge.net
 ***************************************************************************/

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

//////////////////////////////////////////////////////
// Qt specific includes
#include <qdom.h>
#include <qdir.h>
#include <qstringlist.h>
//////////////////////////////////////////////////////
// KDE specific includes
#include <klocale.h>
#include <kconfig.h>
#include <kmdcodec.h>
#include <kmessagebox.h>
#include <kinstance.h>
#include <kgenericfactory.h>
#include <kdebug.h>
//////////////////////////////////////////////////////
// Application specific includes
#include "gftpimportfilterplugin.h"
#include "kbeartags.h"
#include "misc.h"

#include "gftpimportfilterplugin.moc"


using namespace KBear;

typedef KGenericFactory<GFTPImportFilterPlugin> GFTPImportFilterPluginFactory;
K_EXPORT_COMPONENT_FACTORY( kbeargftpimportfilter, GFTPImportFilterPluginFactory( "GFTPImportFilterPlugin" ) );
//-----------------------------------------------
GFTPImportFilterPlugin::GFTPImportFilterPlugin(QObject *parent, const char *name,const QStringList& )
	:	SiteImportFilterPluginIface(parent,name),
		m_hasError( false )
{
//	setXMLFile("gftpimportfilterui.rc");
	KGlobal::locale()->insertCatalogue("kbear");
	m_domDocument.setContent( QString("<%1 %2=\"%3\"/>").arg( TAG_GROUP ).arg( ATT_LABEL ).arg(i18n("gFTP import")) );
}
//-----------------------------------------------
GFTPImportFilterPlugin::~GFTPImportFilterPlugin(){
}
//-----------------------------------------------
QString GFTPImportFilterPlugin::getDomDocument() {
	return m_domDocument.toString();
}
//-----------------------------------------------
void GFTPImportFilterPlugin::import( const QString& fileName ) {
	if( fileName.isEmpty() || fileName.isNull() ) {
		KMessageBox::sorry( 0, i18n("You have to select a file to import."), i18n("No file") );
		m_hasError = true;
		emit progress( 100 );
		return;
	}
	// First we fetch some global settings
	KConfig tmpConfig( QDir::homeDirPath()+"/.gftp/gftprc", true, false, "HOME" );
	QString email = tmpConfig.readEntry( "email", "anonymous@" );	
	int numRetries = tmpConfig.readNumEntry( "retries", -1 );	
	int sleepTime = tmpConfig.readNumEntry( "sleep_time", -1 );	

	KConfig config( fileName, true, false, "HOME" );
	QStringList groupList = config.groupList();
	float size = (float)groupList.count();
	if( size == 0 ) {
		invalidFileError( fileName );
		m_hasError = true;
		emit progress( 100 );
		return;
	}	
	int counter = 0;
	for( QStringList::Iterator it = groupList.begin(); it != groupList.end(); ++it ) {
		QString groupName = *it; // found groupname from gFTP, can have subgroups ( group1/group2/group3 )
		QStringList groupNames = QStringList::split( "/", groupName ); //split group name into subgroups if any

		QDomNode groupNode;
		QDomElement parentElement = m_domDocument.documentElement();
		config.setGroup( groupName );
		QString tmp = config.readEntry("hostname");  // we ignore the site if it hasn't any host
		for( unsigned int i = 0; ! tmp.isNull() && i < groupNames.count() - 1; i++ ) {
			// first see if parenElement has any sub group named *it2
			groupNode = findSubGroup( parentElement, groupNames[ i ] );

			if( groupNode.isNull() ) {
 				// no it had no sub group with the given name
				// so we have to build the sub group tree
				while( i < groupNames.count() -1 ) {
					QDomElement tmpElement = m_domDocument.createElement( TAG_GROUP );
					tmpElement.setAttribute( "label", groupNames[ i ] );
					parentElement.appendChild( tmpElement );	
					parentElement = tmpElement;
					++i;				
				}
			}
			else { // sub group found, lets check next level
				parentElement = groupNode.toElement();
			}
		} // for
		// now group tree is updated so lets create the site
		// first  check so the site has a host, if not ignore it
		if( ! tmp.isNull() ) {  // had host
			// set host
			QDomElement siteElement = m_domDocument.createElement( TAG_SITE );
			siteElement.setAttribute( ATT_LABEL, groupNames.last() );			
			parentElement.appendChild( siteElement );	
			// set host
			tmp = config.readEntry("hostname");
			QDomElement tmpElement = m_domDocument.createElement( TAG_HOST );
			QDomText txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set port
			int p = config.readNumEntry("port", 21 );
			tmpElement = m_domDocument.createElement( TAG_PORT );
			txtNode = m_domDocument.createTextNode( QString::number( p ) );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set protocol
			tmp = config.readEntry("protocol", "ftp" ).lower();
			tmpElement = m_domDocument.createElement( TAG_PROTOCOL );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set remote directory
			tmp = config.readEntry("remote directory", "/");
			tmpElement = m_domDocument.createElement( TAG_REMOTE_PATH );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set local directory
			tmp = config.readEntry("local directory", QDir::homeDirPath());
			tmpElement = m_domDocument.createElement( TAG_LOCAL_PATH );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set username
			tmp = config.readEntry("username", "anonymous");
			tmpElement = m_domDocument.createElement( TAG_USER );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set password
			tmp = config.readEntry("password");
			tmpElement = m_domDocument.createElement( TAG_PASS );
			if( tmp == "@EMAIL@" || tmp.isNull() || tmp.isEmpty() )
				tmp = email;
			 // We have to decode the password
			tmp = encodePassword( tmp );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set username
			if( numRetries >= 0 ) {
				tmpElement = m_domDocument.createElement( TAG_AUTO_RECONNECT );
				siteElement.appendChild( tmpElement );	
				tmpElement.setAttribute(ATT_SLEEP,QString::number( sleepTime ) );
				tmpElement.setAttribute(ATT_COUNT,QString::number( numRetries ) );
			}
		} // for
		emit progress( int(float(counter) / size * 100) );	
		counter++;	
	}	
	emit progress( 100 );
}
//-----------------------------------------------
QDomNode GFTPImportFilterPlugin::findSubGroup( QDomElement parent, const QString& name ) {
	QDomNodeList nodeList = parent.childNodes();
	for( unsigned int i = 0; i < nodeList.count(); i++ ) {
		if( nodeList.item( i ).toElement().attribute(ATT_LABEL) == name )
			return nodeList.item( i );
	}
	return QDomNode();
}
//-----------------------------------------------
void GFTPImportFilterPlugin::invalidFileError(const QString& fileName){
	KMessageBox::sorry( 0, i18n("The file: %1\nis either empty or it's not a valid gFTP bookmarks file.").arg(fileName), i18n("Invalid import file") );
}
//-----------------------------------------------
