#include <klocale.h>
#include <qregexp.h>
#include <qtextcodec.h>
#include <kaction.h>
#include <noatun/stdaction.h>
#include "htmlexport.h"

extern "C"
{
	Plugin *create_plugin()
	{
		return new HTMLExport();
	}
}

HTMLExport::HTMLExport(): QObject(0, "HTMLExport"), Plugin()
{
	NOATUNPLUGINC(HTMLExport);

	mAction = new KAction(i18n("&Export Playlist..."), "saveas", 0,
		this, SLOT(slotExport()), this, "exportlist");
	napp->pluginActionMenu()->insert(mAction);

	new Prefs(this);
	config = KGlobal::config();
}

HTMLExport::~HTMLExport()
{
	napp->pluginActionMenu()->remove(mAction);
}

void HTMLExport::slotExport()
{
	// init readConfig
	config->setGroup("HTMLExport");

	// get output target
	KURL url = KFileDialog::getSaveURL(QString::null,
	                                   "text/html",
	                                   0,
	                                   i18n("Export Playlist"));

	// write into tempfile
	KTempFile temp;
	temp.setAutoDelete(true);
	QFile file(temp.name());
	file.open(IO_WriteOnly);
	QTextStream str(&file);
	str.setCodec(QTextCodec::codecForName("utf8"));

	str << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;
	str << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" << endl;
	str << "<!-- Generated by Noatun " << NOATUN_MAJOR << "." << NOATUN_MINOR << "." << NOATUN_PATCHLEVEL << " -->" << endl;

	str << endl;

	str << "<html>" << endl;
	str << "<head>" << endl;
	str << "\t<title>" << i18n("Noatun Playlist") << "</title>" << endl;

	str << "\t<style type=\"text/css\">" << endl;
	str << "\t\t<!--" << endl;
	// Set the heading color
	str << "\t\th1 { color:#"<< getColorByEntry("headColor")<<"; }" << endl;

	// Optionally set the background image
        if (!config->readPathEntry( "bgImgPath" ).stripWhiteSpace().isEmpty()) {
		// Image
		str << "\t\tp,li { color:#"<< getColorByEntry("txtColor") << "; }" << endl;
		str << "\t\tbody { background-image: url(\"" << config->readPathEntry( "bgImgPath" ) << "\"); }" << endl;
	}
	else {
		// Color
		str << "\t\tp,li,body { color:#"<< getColorByEntry("txtColor");
	        str << "; background-color:#" << getColorByEntry( "bgColor" ) << "; }" << endl;
	}

	// Links are text colored, too
	str << "\t\ta { color:#" << getColorByEntry("txtColor") << "; }" << endl;
	if (getColorByEntry("hoverColor") != getColorByEntry("txtColor"))
		str << "\t\ta:hover { color:#"<< getColorByEntry("hoverColor")<<"; }"<< endl;

	str << "\t\t-->" << endl;
	str << "\t</style>" << endl;

	str << "</head>" << endl;
	str << endl;
	str << "<body>" << endl;
	str << "\t<h1>" << i18n("Noatun Playlist") << "</h1>" << endl;

	// Cache the config settings used in the big loop
	bool link_entries = config->readBoolEntry( "linkEntries" );
	bool number_entries = config->readBoolEntry( "numberEntries" );

	if (number_entries)
		str << "\t\t<ol>" << endl;
	else
		str << "\t\t<p>" << endl;


	for (PlaylistItem item = napp->playlist()->getFirst();item;item = napp->playlist()->getAfter(item)) {
		str << "\t\t\t";

		if (number_entries)
			str << "<li>";

		if (link_entries)
			str << "<a href=\"" << htmlEscape(item.file()) << "\">";

		str << htmlEscape(item.title());

		if (link_entries)
			str << "</a>";

		if (number_entries)
			str << "</li>" << endl;
		else
			str << "<br />" << endl;
	}

	if (number_entries)
		str << "\t\t</ol>" << endl;
	else
		str << "\t\t</p>" << endl;

	str << "\t</body>" << endl;
	str << "</html>" << endl;

	file.close();
	// tempfile -> userdefined file
	KIO::NetAccess::upload(temp.name(), url);
}

QString HTMLExport::htmlEscape(const QString &source) {
	// Escape characters that need to be escaped
	QString temp = source;

	temp.replace( QRegExp("&"), "&amp;" );
	temp.replace( QRegExp("<"), "&lt;" );
	temp.replace( QRegExp(">"), "&gt;" );

	return temp;
}

QString HTMLExport::getColorByEntry(QString s)
{
   QString res;
   QString tmp;
   QColor c;

   // init readConfig

   config->setGroup("HTMLExport");

   c = config->readColorEntry( s );
   tmp = QString::number( c.red(), 16);
   if (tmp.length()==1) tmp="0"+tmp;
   res = tmp;

   tmp = QString::number( c.green(), 16);
   if (tmp.length()==1) tmp="0"+tmp;
   res += tmp;

   tmp = QString::number( c.blue(), 16);
   if (tmp.length()==1) tmp="0"+tmp;
   res += tmp;

   return res;

}
//////////////////////////////////// Settings ////////////////////////////////////

Prefs::Prefs(QObject *parent)
	: CModule(i18n("Playlist Export"), i18n("Colors & Settings for HTML Export"), "html", parent)
{

	// Init Config
	KConfig *config = KGlobal::config();
	config->setGroup("HTMLExport");

	// Set default values
	if ( !config->hasKey( "headColor" ) )
		config->writeEntry( "headColor", QColor( black ) ) ;

	if ( !config->hasKey( "hoverColor" ) )
		config->writeEntry( "hoverColor", QColor( black ) );

	if ( !config->hasKey( "bgColor" ) )
		config->writeEntry( "bgColor", QColor( white ) ) ;

	if ( !config->hasKey( "txtColor" ) )
		config->writeEntry( "txtColor", QColor( black ) );

	config->sync();

	// Draw Stuff and insert Settings
	QVBoxLayout *top = new QVBoxLayout(this, KDialog::marginHint(),
						KDialog::spacingHint() );

	colorBox = new QGroupBox( i18n( "HTML Color Settings"  ), this, "colorBox" );

	bgcolorLabel = new QGridLayout( colorBox, 2, 5,
					KDialog::marginHint(), KDialog::spacingHint() );

	headColorSelect = new KColorButton( colorBox, "headColorSelect" );

	hoverColorSelect = new KColorButton( colorBox, "hoverColorSelect" );

	bgColorSelect = new KColorButton( colorBox, "bgColorSelect" );

	txtColorSelect = new KColorButton( colorBox, "txtColorSelect" );

	txtColorLabel = new QLabel( colorBox, "txtColorLabel" );
	txtColorLabel->setText( i18n( "Text:"  ) );
	txtColorLabel->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

	bgColorLabel = new QLabel( colorBox, "bgColorLabel" );
	bgColorLabel->setText( i18n( "Background:"  ) );
	bgColorLabel->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

	headColorLabel = new QLabel( colorBox, "headColorLabel" );
	headColorLabel->setText( i18n( "Heading:"  ) );
	headColorLabel->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

	hoverColorLabel = new QLabel( colorBox, "hoverColorLabel" );
	hoverColorLabel->setText( i18n( "Link hover:" ) );
	hoverColorLabel->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) );

	bgcolorLabel->setRowStretch(0, 1);

	// Makes the spacing nice
	bgcolorLabel->setColStretch(1, 2);
	bgcolorLabel->setColStretch(2, 1);
	bgcolorLabel->setColStretch(4, 2);

	bgcolorLabel->addWidget( txtColorLabel, 0, 0 );
	bgcolorLabel->addWidget( txtColorSelect, 0, 1 );
	bgcolorLabel->addWidget( headColorLabel, 1, 0 );
	bgcolorLabel->addWidget( headColorSelect, 1, 1 );
	bgcolorLabel->addWidget( bgColorLabel, 0, 3 );
	bgcolorLabel->addWidget( bgColorSelect, 0, 4 );
	bgcolorLabel->addWidget( hoverColorLabel, 1, 3 );
	bgcolorLabel->addWidget( hoverColorSelect, 1, 4 );


	// Set up the Background Image frame
	bgPicBox = new QHGroupBox( i18n( "Background Image"), this, "bgPicBox" );

	// Set up the URL requestor
	bgPicPath = new KURLRequester ( bgPicBox, "bgPicPath" );
	bgPicPath->setShowLocalProtocol(true);

	// Set up the URL requestor's file dialog
	bgPicPath->setMode(KFile::File | KFile::ExistingOnly);
	bgPicPath->setFilter("image/gif image/jpeg image/gif image/png image/svg+xml image/tiff");

	linkEntries = new QCheckBox( this, "linkEntries" );
	linkEntries->setText( i18n( "Hyper&link playlist entries to their URL"  ) );
	linkEntries->setTristate( false );

	numberEntries = new QCheckBox( this, "numberEntries" );
	numberEntries->setText( i18n( "&Number playlist entries"  ) );
	numberEntries->setTristate( false );

	top->addWidget( colorBox );
	top->addWidget( bgPicBox );
	top->addWidget( linkEntries );
	top->addWidget( numberEntries );

	top->addStretch();

    reopen();
}

void Prefs::save()
{
	KConfig *config = KGlobal::config();

	QString bgRealURL = bgPicPath->url();

	if (bgRealURL[0] == '/')
		bgRealURL = "file:" + bgRealURL;

	config->setGroup( "HTMLExport" );
	config->writeEntry( "bgColor", bgColorSelect->color() );
	config->writeEntry( "txtColor", txtColorSelect->color() );
	config->writeEntry( "headColor", headColorSelect->color() );
	config->writeEntry( "hoverColor", hoverColorSelect->color() );
	config->writePathEntry( "bgImgPath", bgRealURL );
	config->writeEntry( "linkEntries", linkEntries->isChecked() );
	config->writeEntry( "numberEntries", numberEntries->isChecked() );
	config->sync();
}

void Prefs::reopen()
{
	KConfig *config = KGlobal::config();
	headColorSelect->setColor(config->readColorEntry( "headColor" ) );
	hoverColorSelect->setColor( config->readColorEntry( "hoverColor" ) );
	bgColorSelect->setColor( config->readColorEntry( "bgColor" ) );
	txtColorSelect->setColor( config->readColorEntry( "txtColor" ) );
	bgPicPath->setURL( config->readPathEntry( "bgImgPath" ) );
	numberEntries->setChecked( config->readBoolEntry( "numberEntries" ) );
	linkEntries->setChecked( config->readBoolEntry( "linkEntries" ) );
}
#include "htmlexport.moc"

