/***************************************************************************
 *   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 <qcheckbox.h>
#include <qregexp.h>

#include <klineedit.h>
#include <klocale.h>
#include <ktextedit.h>
#include <kmessagebox.h>
#include <kcombobox.h>
#include <kpushbutton.h>
#include <kiconloader.h>
#include <kdatetimewidget.h>
#include <qpixmap.h>
#include <qstylesheet.h>
#include <kdebug.h>
#include <kurl.h>

#include "kbloggerconfigdialog.h"
#include "kbloggerconfig.h"
#include "kbloggerlinkdialog.h"
#include "kbloggerhtmldialog.h"

#include "kbloggereditor.h"
#include "API_Blog.h"


KBloggerEditor::KBloggerEditor( KBlog::APIBlog* backend, int postid, QWidget* parent, const char* name, WFlags fl)
        : KBloggerEditorBlank(parent,name,fl), m_postid( postid ), m_linkDialog(), m_htmlDialog()
{
	kdDebug() << "KBloggerEditor::KBloggerEditor()" << endl;
	if(!m_backend) this->close();
	m_backend=backend;
	m_linkDialog=new KBloggerLinkDialog(this);
	m_htmlDialog=new KBloggerHtmlDialog(this);

	kdDebug() << "initialize Buttons" << endl;
	BoldButton->setPixmap( BarIcon( QString::fromLatin1("text_bold") ) );
	ItalicButton->setPixmap( BarIcon( QString::fromLatin1("text_italic") ) );
	connect( ItalicButton, SIGNAL( clicked() ),
			this, SLOT( toggleItalic() ) );
	connect( BoldButton, SIGNAL( clicked() ),
			this, SLOT( toggleBold() ) );
	connect( LinkButton, SIGNAL( clicked() ),
			this, SLOT( linkDialogSlot() ) );
	connect( HtmlButton, SIGNAL( clicked() ),
			this, SLOT( htmlDialogSlot() ) );

	kdDebug() << "interfaceName() " << backend->interfaceName() << endl;

	ContentTextEditor->setCheckSpellingEnabled (true); // enable spell checking

	if( m_backend->interfaceName()!= "Blogger API 1.0") { // Only Blogger API doesn't support a title and categories
		TitleLineEdit->setReadOnly( false ); 
		CategoryComboBox->setEditable( true );
		TimeStampCheckBox->setEnabled(true);
		KIO::TransferJob *catjob = m_backend->createListCategoriesJob( KURL::KURL( KBloggerConfig::blogId() ) );
		connect(catjob, SIGNAL( result( KIO::Job* ) ),
				m_backend, SLOT( interpretListCategoriesJob( KIO::Job* ) ) );
		connect( m_backend, SIGNAL( categoryInfoRetrieved( const QString&, const QString& ) ),
				this, SLOT( getCategoriesSlot( const QString&, const QString& ) ) );
		connect( m_backend, SIGNAL( fetchingCategoriesFinished() ),
				this, SLOT( disconnectCategoriesSlot() ) );
	}

	kdDebug() << "m_postid: " << m_postid << endl;
	if( m_postid!=-1 ){
		kdDebug() << "Creating new DownloadJob at " << m_postid << endl;
		KIO::TransferJob *editjob = m_backend->createDownloadJob( KURL::KURL( QString( "%1").arg( m_postid ) ) );
		connect(editjob, SIGNAL( result( KIO::Job* ) ),
				m_backend, SLOT( interpretDownloadItemsJob( KIO::Job* ) ) );
		connect( m_backend, SIGNAL( itemOnServer( KBlog::BlogPosting& ) ),
				this, SLOT( loadPostSlot( KBlog::BlogPosting& ) ) );
	}

	connect (m_linkDialog, SIGNAL( addLink( QString, QString ) ),
			this, SLOT( addHtmlLink( QString, QString ) ) );
	connect (m_htmlDialog, SIGNAL( addHtmlCode( QString ) ),
			this, SLOT( addHtmlCode( QString ) ) );

	connect(m_backend, SIGNAL( error( const QString& ) ), 
			this, SLOT( handleBackendError( const QString& ) ) );// actually this can be called from elsewhere, too, but this shouldn't be a problem since we only want to release the send button

	//Update KTimeStamp Widget
	TimeStampKDateTime->setDateTime(QDateTime::currentDateTime());
	show();	
}

void KBloggerEditor::handleSuccess( const int id ){
	KMessageBox::information( 0, i18n( "Element %1 posted." ).arg( id )  );
	close();
}

void KBloggerEditor::handleBackendError( const QString& error ){
	SendButton->setEnabled(true);
}

KBloggerEditor::~KBloggerEditor()
{
	kdDebug() << "KBloggerEditor::~KBloggerEditor()" << endl;
	//delete m_linkDialog; // it's a child of this class then will be auto deleted!
}

void KBloggerEditor::toggleItalic(){
	ContentTextEditor->setItalic( !ContentTextEditor->italic() );
}

void KBloggerEditor::toggleBold(){
	ContentTextEditor->setBold( !ContentTextEditor->bold() );
}
void KBloggerEditor::disconnectCategoriesSlot() {
	disconnect( dynamic_cast<QObject*>( m_backend ), SIGNAL( categoryInfoRetrieved( const QString&, const QString& ) ),
				dynamic_cast<QObject*>( this ), SLOT( getCategoriesSlot( const QString&, const QString& ) ) );
}

void KBloggerEditor::linkDialogSlot(){
	m_linkDialog->setName( ContentTextEditor->selectedText());
	m_linkDialog->show();
}

void KBloggerEditor::htmlDialogSlot(){
	m_htmlDialog->show();
}

void KBloggerEditor::addHtmlLink( QString target, QString name ){
	ContentTextEditor->append( "<a href=\"" + target + "\">" + name + "</a>" );
}

void KBloggerEditor::addHtmlCode( QString code ){
	ContentTextEditor->append( code );
}

void KBloggerEditor::loadPostSlot( KBlog::BlogPosting& posting ){
	kdDebug() << "KBloggerEditor::loadPostSlot()" << endl;
	TitleLineEdit->setText( posting.title() );
	CategoryComboBox->setCurrentText( posting.category() );
	ContentTextEditor->setText( posting.content() );
	disconnect( dynamic_cast<QObject*>( m_backend ), SIGNAL( itemOnServer( KBlog::BlogPosting& ) ),
				dynamic_cast<QObject*>( this ), SLOT( loadPostSlot( KBlog::BlogPosting& ) ) );
}

/*$SPECIALIZATION$*/

void KBloggerEditor::sendSlot()
{
	kdDebug() << "KBloggerEditor::sendSlot()" << endl;
	if( !TitleLineEdit->isReadOnly() && TitleLineEdit->text().isEmpty() )
		if( KMessageBox::questionYesNo( 0, 
		i18n("Are you sure you want to send without title?")  )!=3 ) // this is no good... the code for KDialog::ButtonCode Yes 
	return;
	if( ContentTextEditor->text().isEmpty() )
		if( KMessageBox::questionYesNo( 0, 
		i18n("Are you sure you want to send without content?")  )!=3 ) // this is no good... the code for KDialog::ButtonCode Yes 
	return;

	kdDebug() << "KBlog::BlogPosting()" << endl;
	SendButton->setEnabled(false);
	connect(m_backend, SIGNAL( uploadPostId( const int ) ),
			this, SLOT( handleSuccess( const int ) ) );
	KBlog::BlogPosting *posting = new KBlog::BlogPosting();
	posting->setBlogID( KBloggerConfig::blogId() );
	posting->setTitle( TitleLineEdit->text() );

	// HACK ? changing richtext content
	QString richText = ContentTextEditor->text();
	richText.remove( "<html><head><meta name=\"qrichtext\" content=\"1\" /></head>" );
	richText.remove( QRegExp("<body[^<]+>") );
	richText.remove( QRegExp("<[^<]+color:#ff0000[^>]+>") ); // FIXME gets really dirty here, removing spell checking red
	richText.remove( "</p>\n</body></html>" );
	richText.remove( "<p>" );
	richText.remove( "</p>" );
	posting->setContent( richText );
	posting->setPublish( PublishCheckbox->isChecked() );
	posting->setCategory( CategoryComboBox->currentText() );
        if ( TimeStampKDateTime->isEnabled() )
	  posting->setCreationDateTime( TimeStampKDateTime->dateTime() );
	KIO::TransferJob* uploadjob;
	if( m_postid!=-1 ){
		kdDebug() << "Creating m_backend->createUploadJob()" << endl;
		posting->setPostID( QString("%1").arg(m_postid) );
		uploadjob = m_backend->createUploadJob( KURL::KURL( m_postid ), posting );
	}
	else {
		kdDebug() << "Creating m_backend>createUploadNewJob()" << endl;
		uploadjob = m_backend->createUploadNewJob( posting );
	}
	connect( uploadjob, SIGNAL( result( KIO::Job* ) ),
			m_backend, SLOT( interpretUploadJob( KIO::Job* ) ) );
	connect( m_backend, SIGNAL( uploadPostId( const int ) ),
			this, SLOT( closeSignal( const int ) ) );
}

void KBloggerEditor::closeSignal( const int ){
	this->close();
}

void KBloggerEditor::getCategoriesSlot( const QString &name, const QString &description ){
	kdDebug() << "KBloggerEditor::getCategoriesSlot()" << endl;
	if( !CategoryComboBox->currentText().isEmpty() ){
		m_editCategory = CategoryComboBox->currentText();
		CategoryComboBox->insertItem( name );
		CategoryComboBox->setEditText( m_editCategory );
	}
	else
		CategoryComboBox->insertItem( name );
}

#include "kbloggereditor.moc"
