/***************************************************************************
                          krusaderimportfilterplugin.h  -  description
                             -------------------
    begin                : fre aug 09 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 "krusaderimportfilterplugin.h"
#include "kbeartags.h"
#include "misc.h"

#include "krusaderimportfilterplugin.moc"

using namespace KBear;

typedef KGenericFactory<KrusaderImportFilterPlugin> KrusaderImportFilterPluginFactory;
K_EXPORT_COMPONENT_FACTORY( kbearkrusaderimportfilter, KrusaderImportFilterPluginFactory( "KrusaderImportFilterPlugin" ) );
//-----------------------------------------------
KrusaderImportFilterPlugin::KrusaderImportFilterPlugin(QObject *parent, const char *name,const QStringList& )
	:	SiteImportFilterPluginIface(parent,name),
		m_hasError( false )
{
//	setXMLFile("krusaderimportfilterui.rc");
	KGlobal::locale()->insertCatalogue( QString::fromLatin1("kbear" ));
	m_domDocument.setContent( QString("<%1 %2=\"%3\"/>").arg(TAG_GROUP).arg(ATT_LABEL).arg(i18n("Krusader import")) );
}
//-----------------------------------------------
KrusaderImportFilterPlugin::~KrusaderImportFilterPlugin(){
}
//-----------------------------------------------
QString KrusaderImportFilterPlugin::getDomDocument() {
	return m_domDocument.toString();
}
//-----------------------------------------------
void KrusaderImportFilterPlugin::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;
	}
	KConfig tmpConfig( QString::fromLatin1("krusaderrc"), true, false );
	tmpConfig.setGroup( QString::fromLatin1("RemoteMan") );
	QStringList groupList = tmpConfig.readListEntry( QString::fromLatin1("Connections") );
	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 Krusader, can have subgroups ( group1`group2`group3 )
		if( groupName == QString::fromLatin1("expanded") || groupName == QString::fromLatin1("collapsed") ) // ignore these - no group names
          	continue;

		QStringList groupNames = QStringList::split( '`', groupName ); //split group name into subgroups if any

		QDomNode groupNode;
		QDomElement parentElement = m_domDocument.documentElement();
		QStringList siteInfoList = tmpConfig.readListEntry( groupName );  // we ignore the site if it hasn't any host
		if( ! (siteInfoList.count() > 1) || siteInfoList[ 1 ].left( 5 ) == QString::fromLatin1("GROUP") ) // we ignore group names 
			continue;
		QString tmp = QString::null;
		if( siteInfoList.count() > 2 ) {
			tmp = siteInfoList[ 2 ];
		}
		for( unsigned int i = 0; ! tmp.isEmpty() && 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( ATT_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 site
			QDomElement siteElement = m_domDocument.createElement( TAG_SITE );
			siteElement.setAttribute( ATT_LABEL, groupNames.last() );			
			parentElement.appendChild( siteElement );	
			// set host
			tmp = siteInfoList[ 2 ];
			QDomElement tmpElement = m_domDocument.createElement( TAG_HOST );
			QDomText txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set port
			if( siteInfoList.count() < 4 )
				continue;
			int p = siteInfoList[ 3 ].toInt();
			tmpElement = m_domDocument.createElement( TAG_PORT );
			txtNode = m_domDocument.createTextNode( QString::number( p ) );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
			// set username
			if( siteInfoList.count() < 5 )
				continue;
			tmp = siteInfoList[ 4 ];
			tmpElement = m_domDocument.createElement( TAG_USER );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );
			// set password
			if( siteInfoList.count() < 6 )
				continue;
			tmp = siteInfoList[ 5 ];
			tmpElement = m_domDocument.createElement( TAG_PASS );
			 // We have to decode the password
			tmp = encodePassword( tmp );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );
			// set remote directory
			if( siteInfoList.count() < 7 )
				continue;
			tmp = siteInfoList[ 6 ];
			tmpElement = m_domDocument.createElement( TAG_REMOTE_PATH );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );
			// set local directory
			tmp = QDir::homeDirPath();
			tmpElement = m_domDocument.createElement( TAG_LOCAL_PATH );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );
			// set description
			if( siteInfoList.count() < 8 )
				continue;
			tmp = siteInfoList[ 7 ];
			tmpElement = m_domDocument.createElement( TAG_DESCRIPTION );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );
			// set protocol
			if( siteInfoList.count() < 9 )
				continue;
			tmp = siteInfoList[ 8 ];
			p = tmp.find( QString::fromLatin1("://") );
			tmp = tmp.left( p );
			tmpElement = m_domDocument.createElement( TAG_PROTOCOL );
			txtNode = m_domDocument.createTextNode( tmp );
			tmpElement.appendChild( txtNode );
			siteElement.appendChild( tmpElement );	
		} // for
		emit progress( int(float(counter) / size * 100) );	
		counter++;	
	}	
	emit progress( 100 );
}
//-----------------------------------------------
QDomNode KrusaderImportFilterPlugin::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 KrusaderImportFilterPlugin::invalidFileError(const QString& fileName){
	KMessageBox::sorry( 0, i18n("The file: %1\nis either empty or it's not a valid Krusader bookmarks file.").arg(fileName), i18n("Invalid import file") );
}
//-----------------------------------------------
