#include <klocale.h>
#include <tqregexp.h>
#include <tqtextcodec.h>
#include <kaction.h>
#include <noatun/stdaction.h>
#include "htmlexport.h"

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

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

	mAction = new KAction(i18n("&Export Playlist..."), "filesaveas", 0,
		this, TQT_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(TQString(),
	                                   "text/html",
	                                   0,
	                                   i18n("Export Playlist"));

	// write into tempfile
	KTempFile temp;
	temp.setAutoDelete(true);
	TQFile file(temp.name());
	file.open(IO_WriteOnly);
	TQTextStream str(&file);
	str.setCodec(TQTextCodec::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, 0);
}

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

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

	return temp;
}

TQString HTMLExport::getColorByEntry(TQString s)
{
   TQString res;
   TQString tmp;
   TQColor c;

   // init readConfig

   config->setGroup("HTMLExport");

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

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

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

   return res;

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

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

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

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

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

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

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

	config->sync();

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

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

	bgcolorLabel = new TQGridLayout( 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 TQLabel( colorBox, "txtColorLabel" );
	txtColorLabel->setText( i18n( "Text:"  ) );
	txtColorLabel->tqsetAlignment( int( TQLabel::AlignVCenter | TQLabel::AlignRight ) );

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

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

	hoverColorLabel = new TQLabel( colorBox, "hoverColorLabel" );
	hoverColorLabel->setText( i18n( "Link hover:" ) );
	hoverColorLabel->tqsetAlignment( int( TQLabel::AlignVCenter | TQLabel::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 TQHGroupBox( 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 TQCheckBox( this, "linkEntries" );
	linkEntries->setText( i18n( "Hyper&link playlist entries to their URL"  ) );
	linkEntries->setTristate( false );

	numberEntries = new TQCheckBox( 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();

	TQString 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"