/***************************************************************************
 *   Copyright (C) 2005 by Christian Weilbach   *
 *   christian_weilbach@web.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.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


#include <qlayout.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qsize.h>
#include <qpixmap.h>
#include <qcursor.h>

#include <kaboutdata.h>
#include <kaboutapplication.h>
#include <kaboutdialog.h>
#include <kbugreport.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfigdialog.h>
#include <kapplication.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kio/job.h>
#include <kstartupinfo.h>
// #include <kiconloader.h>

#include "kblogger.h"

// #if KDE_IS_VERSION(3,5,0)
// #include "kbloggerbutton.h"
// #endif

#include "kbloggermenu.h"
#include "kbloggerconfigdialog.h"
#include "kbloggerconfig.h"
#include "kbloggereditor.h"
#include "kbloggerupload.h"
#include "API_Blogger.h"
#include "API_MetaWeblog.h"

const int BLOGGER_API=0;
const int METAWEBLOG_API=1;

class KBloggerMenu;

KBlogger::KBlogger(const QString& configFile, Type type, int actions, QWidget *parent, const char *name)
        : KPanelApplet(configFile, type, actions, parent, name), m_backend( 0 ), m_editor( 0 ), m_upload( 0 ), m_button( 0 )

{
	updateBackend();

	// create menu
	m_menu=new KBloggerMenu( m_backend, this, "menu" );
	setCustomMenu(m_menu);

	// create the applet-widget
	kdDebug() << "Creating Applet-widget";
// #if KDE_IS_VERSION(3,5,0)
// 	kdDebug() << " for >3.5.0" << endl;
// 	m_button =  new KBloggerButton(this);
// 	m_button->setPanelPosition( position() );
// #else
// // Old code, maybe check for kde 3.5
// 	kdDebug() << " for <3.5.0" << endl;
 	QVBoxLayout *appletlay = new QVBoxLayout(this);
 	m_button = new QPushButton( i18n("blog"),this );
 	appletlay->addWidget(m_button);
	connect(m_button, SIGNAL(clicked()), this, SLOT(slotClicked()));
// #endif


	if (!parent)
		setBackgroundMode(X11ParentRelative);

	setAcceptDrops(true);

	// initialize about data
	m_aboutData = new KAboutData("kblogger", I18N_NOOP("KBlogger"), 
				"0.6.5", I18N_NOOP("A kicker applet for blogging."), KAboutData::License_GPL, 
				0, 0, "http://kblogger.pwsp.net", "christian_weilbach@web.de");
	m_aboutData->addAuthor ( "Christian Weilbach", I18N_NOOP("Main developer"), 
				I18N_NOOP("christian_weilbach@web.de"), I18N_NOOP("whiletaker.homeip.net"));
	m_aboutData->addAuthor ( "Antonio Aloisio", I18N_NOOP("Developer") );
	m_aboutData->addAuthor ( "Harald Sitter", I18N_NOOP("Documentation and Support") );
	m_aboutData->addAuthor ( "Kenneth Wimer", I18N_NOOP("Icon designer") );

	// initialize configuration
	kdDebug() << "Creating KConfigDialog"  <<  endl;
	m_configDialog = new KConfigDialog( this, "settings", KBloggerConfig::self(), KDialogBase::Plain );
	m_configwd = new KBloggerConfigDialog();
	m_configDialog->addPage( m_configwd, i18n("KBlogger settings"), "KBlogger settings" );
	m_configDialog->setInitialSize( QSize( 520, 300 ), false ); // FIXME

	connect(m_backend, SIGNAL( error( const QString& ) ),
			this, SLOT( handleBackendError( const QString& ) ) );
	connect(m_configDialog, SIGNAL( settingsChanged() ), 
			this, SLOT( updateBackend() ) );
	connect(m_backend, SIGNAL( mediaInfoRetrieved( const QString& ) ),
			this, SLOT( handleSuccess( const QString& ) ) );

	KStartupInfo::appStarted();
}

void KBlogger::slotClicked()
{
// 	mFileItem.run();
	editorSlot();
}

KBlogger::~KBlogger()
{
	kdDebug() << "KBlogger::~KBlogger()" << endl;
	delete m_backend;
	delete m_aboutData;
	delete m_configwd;
	delete m_configDialog;
	delete m_editor;
}

void KBlogger::handleSuccess( const QString& string ){
	KMessageBox::information( 0, i18n( "Element %1 posted." ).arg( string )  );
}

void KBlogger::menuSlot() {
	kdDebug() << "KBlogger::menuSlot()" << endl;
	if( KBloggerConfig::type() != BLOGGER_API ) m_menu->setFullMenu( true );
	m_menu->setPosition( QCursor::pos() );
	m_menu->populateMenu();
}

void KBlogger::updateBackend(){
	// close all open widgets
// 	if( m_editor ) m_editor->close();
// 	if( m_upload ) m_upload->close();

	// delete old backend, if available FIXME memory leak, but shouldn't be heavy
// 	delete m_backend;
// 	m_backend=0;

	kdDebug() << "Creating KURL" << endl;
	KURL mServerUrl(  KBloggerConfig::url() );

	// create the backend
	kdDebug() << "API type =" << KBloggerConfig::type() << endl;
	switch( KBloggerConfig::type() ){
		case BLOGGER_API:
		kdDebug() << "Creating APIBlogger( '"<< KBloggerConfig::url() << "' )" << endl;
		m_backend = new KBlog::APIBlogger( mServerUrl ); 
		m_backend->setAppID( "0123456789ABCDEF" ); // id not needed anymore
		break;

		case METAWEBLOG_API:
		m_backend = new KBlog::APIMetaWeblog( mServerUrl ); 
		break;

		default:
		KMessageBox::error( 0, i18n( "API Type not found. You have to configure first." ) );
		m_backend=0;
		return;
		break;
	}
	m_backend->setUsername( KBloggerConfig::user() );
	m_backend->setPassword( KBloggerConfig::password() );
}


void KBlogger::editorSlot(){
	kdDebug() << "KBlogger::editorSlot()" << endl;
// 	delete m_editor; // ist deleted through close-button?
	m_editor = new KBloggerEditor( this->m_backend );
}

void KBlogger::editorSlot( int postid ){
	kdDebug() << "KBlogger::editorSlot()" << endl;
// 	delete m_editor;
	m_editor = new KBloggerEditor( this->m_backend, postid );
}

void KBlogger::uploadSlot( QString filename ){
	kdDebug() << "KBlogger::uploadSlot()" << endl;
// 	delete m_upload;
	m_upload =  new KBloggerUpload( this->m_backend, filename );
}

void KBlogger::uploadSlot(){
	this->uploadSlot( QString() );
}

void KBlogger::handleBackendError( const QString& error ){
	KMessageBox::error( 0, i18n( error )  );
}

void KBlogger::about()
{
	kdDebug() << "KBlogger::about()" << endl;

	KAboutApplication aboutdialog( m_aboutData );
	aboutdialog.exec();
}

void KBlogger::reportBug()
{
	KBugReport bugReport(this, true, m_aboutData);
	bugReport.exec();
}

void KBlogger::help()
{
	kapp->invokeHelp(QString::null, QString::fromLatin1("kblogger"));
}


void KBlogger::preferences()
{
	m_configDialog->show();
}

int KBlogger::widthForHeight( int height ) const
{
	return 60;
}

int KBlogger::heightForWidth( int width ) const
{
	return 60;
}

void KBlogger::resizeEvent( QResizeEvent * )
{
// #if KDE_IS_VERSION(3,5,0)
// 	if (!m_button)
// 	{
// 		return;
// 	}
// 
// 	int size = 1;
// 
// 	size = std::max( size, 
// 			 orientation() == Qt::Vertical ?
// 			 	m_button->heightForWidth( width() ) :
// 				m_button->widthForHeight( height() ) );
// 
// 	
// 	if(orientation() == Vertical)
// 	{
// 		m_button->resize( width(), size );
// 	}
// 	else
// 	{
// 		m_button->resize( size, height() );
// 	}
// #endif
}

void KBlogger::mousePressEvent(QMouseEvent *e)
{
	if (e->button() == QMouseEvent::RightButton)
		menuSlot();
}


extern "C"
{
	KPanelApplet* init( QWidget *parent, const QString& configFile)
	{
		KGlobal::locale()->insertCatalogue("kblogger");
		return new KBlogger(configFile, KPanelApplet::Normal,
				KPanelApplet::About | KPanelApplet::Help | KPanelApplet::Preferences,
				parent, "kblogger");
	}
}
