/***************************************************************************
                          siteimportwidget.cpp  -  description
                             -------------------
    begin                : sat feb 1 2003
    copyright            : (C) 2003 by Frithjof Engel
    email                : frithjof_engel@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 include files
#include <qlayout.h>
#include <qdir.h>
#include <qlabel.h>
#include <qfile.h>
#include <qptrlist.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
//////////////////////////////////////////////////////////////////////
// KDE specific include files
#include <klistview.h>
#include <kpushbutton.h>
#include <kprogress.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klibloader.h>
#include <kstandarddirs.h>
#include <kparts/plugin.h>
#include <kfiledialog.h>
//////////////////////////////////////////////////////////////////////
// Application specific include files
#include "siteimportwidget.h"

using namespace KBear;
KBearSiteImportWidget::KBearSiteImportWidget( QWidget *parent, const char *name )
	: QWidget( parent, name ),
	m_importPlugin( 0L )
{
	setupGUI();
	connect( m_filtersListView, SIGNAL( selectionChanged() ), this, SLOT( slotSelectionChanged() ) );
    connect( m_importButton, SIGNAL( clicked() ), this, SLOT( slotImport() ) );
	
	m_pluginList = KTrader::self()->query("KBear/SiteImportFilter");
	KTrader::OfferList::Iterator it( m_pluginList.begin() );
	for( ; it != m_pluginList.end(); ++it ) {
		KService::Ptr ptr = (*it);
		QListViewItem* item = new QListViewItem( m_filtersListView, ptr->name() );	
		item->setPixmap( 0, KGlobal::iconLoader()->loadIcon("filter", KIcon::Small ) );
		item->setExpandable( false );
	}
}
//-----------------------------------------------
KBearSiteImportWidget::~KBearSiteImportWidget() {
}
//-----------------------------------------------
void KBearSiteImportWidget::setupGUI() {
	m_importLayout = new QGridLayout( this, 0, 0, 11, 6 );
 	m_vboxLayout = new QVBoxLayout( this, 0 );
	
	QLabel* infoLabel = new QLabel( this );
	infoLabel->setText( i18n( "<p>This page let you import bookmarks from various applications. "
															"Just select a filter from the list below and push the <b>Import</b> button</p>" ) );
	infoLabel->setAlignment( int( QLabel::WordBreak | QLabel::AlignTop ) );

	m_filtersListView = new KListView( this );
	m_filtersListView->setFullWidth( true );
	m_filtersListView->addColumn( i18n( "Available filters" ) );
	QString tmp = i18n("This list shows all available  import filters.");
	QToolTip::add( m_filtersListView, tmp );
	QWhatsThis::add( m_filtersListView, tmp + i18n("  Select a filter and push the import button to import the bookmarks.") );
	m_importButton = new KPushButton( i18n( "Import" ), this );
	m_importButton->setEnabled( false );
	tmp = i18n("Push this button to import bookmarks with the selected filter.");
	QToolTip::add( m_importButton, tmp );
	QWhatsThis::add( m_importButton, tmp );
	m_importProgress = new KProgress( 100, this );
	m_spacer = new QSpacerItem( 0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding );
 	m_vboxLayout->addItem( m_spacer );
 	m_vboxLayout->addWidget( m_importButton );
 	m_vboxLayout->addWidget( m_importProgress );
	m_importLayout->addMultiCellWidget( infoLabel, 0, 0, 0, 1 );
	m_importLayout->addMultiCellWidget( m_filtersListView, 1, 2, 0, 0 );
 	m_importLayout->addLayout( m_vboxLayout, 1, 1 );
}
//-----------------------------------------------
void KBearSiteImportWidget::slotImport(){
	if( ! m_filtersListView->selectedItem() ) // no selected filter
		return;
	KTrader::OfferList::Iterator it( m_pluginList.begin() );
	for( ; it != m_pluginList.end(); ++it ) {
		KService::Ptr ptr = (*it);
		if( m_filtersListView->selectedItem()->text(0) ==  ptr->name() ) {	
			QString fileName = ptr->property( "X-KBear-ImportFile" ).toString();
			// check if a filename was given
			if( ! fileName.isEmpty() ) {  // locate the file
				KGlobal::dirs()->addResourceDir( "HOME", QDir::homeDirPath() );
				QString tmp = fileName;
				fileName = locate( "data", tmp );
				if( fileName.isEmpty() ) {// not found in data
					fileName = locate( "appdata", tmp ); // so try in data
					if( fileName.isEmpty() ) {// not found in appdata
						fileName = locate( "config", tmp );  // so try in config
						if( fileName.isEmpty() ) {// not found in config
							fileName = locate( "HOME", tmp ); // so try in HOME
						}
					}
				}
			}
			if( fileName.isEmpty() ) {
				fileName = KFileDialog::getOpenFileName( QDir::homeDirPath(), QString::null, this,
													i18n("Select file to import with %1").arg(ptr->name()) );
			}
			if( ! fileName.isEmpty() ) {
                   KLibFactory* factory = KLibLoader::self()->factory( ptr->library().latin1() );
				if( factory ) {
					SiteImportFilterPluginIface* plugin = static_cast<SiteImportFilterPluginIface*>(factory->create( this, "ImportFilter", "KParts::Plugin" ));
					if( plugin )
						startImport( plugin, fileName );
				}
			}
		}
	}	
}
//-----------------------------------------------
void KBearSiteImportWidget::startImport( SiteImportFilterPluginIface* importPlugin, const QString& fileName ) {
	m_importPlugin = importPlugin;
	connect( importPlugin, SIGNAL( progress( int ) ), this, SLOT( slotProgress( int ) ) );
	m_importProgress->setValue( 0 );
	importPlugin->import( fileName );
}
//-----------------------------------------------
void KBearSiteImportWidget::slotProgress( int progress ) {
	m_importProgress->setProgress( progress );
	if( progress == 100 ) {
		// When we get here the import should be done so lets fetch the dom tree
		if( ! m_importPlugin->hasError() )  {
			emit importSites( m_importPlugin->getDomDocument() );
		}
		delete m_importPlugin;
		m_importProgress->setValue( 0 );
	}
}
//-----------------------------------------------
void KBearSiteImportWidget::slotSelectionChanged(){
	m_importButton->setEnabled( m_filtersListView->selectedItem() );
}
//-----------------------------------------------
