/***************************************************************************
 *   Copyright (C) 2004, 2005 Thomas Nagy                                  *
 *   tnagy2^8@yahoo.fr                                                     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License version 2        *
 *   as published by the Free Software Foundation (see COPYING)            *
 *                                                                         *
 *   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.                          *
 ***************************************************************************/

#include <qdir.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qmap.h>
#include <qpixmap.h>
#include <qtextcodec.h>
#include <qregexp.h>

#include <kurl.h>
#include <klocale.h>
#include <kdebug.h>
#include <ktempdir.h>
#include <kgenericfactory.h>

#include "settings.h"
#include "datastruct/aux.h"
#include "datastruct/DItem.h"
#include "datastruct/DDataControl.h"
#include "datastruct/DDataItem.h"

#include "kdisshtmldoc.h"

K_EXPORT_COMPONENT_FACTORY(libkdisshtmldoc, kdisshtmldocFactory)
	QObject *kdisshtmldocFactory::createObject(QObject *, const char *, const char *, const QStringList &) { return new kdisshtmldoc; }

	static const int maxpicsize = 700;

	// quick function to get rid only of the annoying tags: html, body..
QString cleanHTML(const QString &src)
{
	QString ret = src;

	ret.replace("<html>", QString::null);
	ret.replace("</html>", QString::null);

	ret.replace("</body>", QString::null);

	QRegExp rx("<body.*>");
	rx.setMinimal(true);
	ret.replace(rx, QString::null);

	QRegExp ry("<head>.*</head>");
	ry.setMinimal(true);
	ret.replace(ry, QString::null);

	//kdWarning()<<"returned:"<<ret<<endl;
	return ret;
}

kdisshtmldoc::kdisshtmldoc() : DGenerator()
{
	m_cnt_lev1 = 0;
	m_cnt_lev2 = 0;
	m_cnt_lev3 = 0;
}

kdisshtmldoc::~kdisshtmldoc() { }

const QString kdisshtmldoc::identifikation()
{
	return "kdisshtmldoc";
}

const QString kdisshtmldoc::fullName()
{
	return i18n("Single HTML Page");
}

const QString kdisshtmldoc::group()
{
	return i18n("HTML");
}

const QString kdisshtmldoc::description()
{
	return i18n("This template generates an html document (one page including pictures) that can be viewed using a web browser (konqueror for example)");
}

const QString kdisshtmldoc::quickstart()
{
	return i18n("Go into the directory created and view main.html with a web browser (eg: konqueror)\n");
}

void outputPixParagraph(DDataItem* item, QTextStream & s)
{
	if (item->m_pix.isNull())
		return;

	int width = item->m_pix.width();
	int height = item->m_pix.height();

	int newwidth = width;
	int newheight = height;

	if (width > maxpicsize)
	{
		newwidth = maxpicsize;
		newheight = height*newwidth/width;
	}
	else if (height > maxpicsize)
	{
		newheight = maxpicsize;
		newwidth = width*newheight/height;
	}


	// TODO: this item caption is not perfect
	s<<"<p>\n";
	s<<"<img src=\"pics/"<<item->m_picfilename<<
		"\" alt=\"pic-"<<QString::number(item->Id())<<
		"\" height=\""<<newheight<<"\" width=\""<<newwidth<<"\" />";
	s<<"\n</p>\n";

	s<<"<p>\n";
	if (item->m_piccaption.length() > 0)
		s<<DDataItem::protectXML(item->m_piccaption);
	s<<"\n</p>\n";
}

void outputLinks(DDataItem* item, QTextStream & s)
{
	for (unsigned int i=0; i<item->m_urllist.count(); i++)
	{
		QString url = item->m_urllist[i].m_url;
		QString caption = item->m_urllist[i].m_caption;
		
		if (!caption.length()) caption = url;
		
		// XXX i still do not think it is necessary to escape the url
		//  '&' chars are allowed here
		s<<"<p>\n";
		s<<" <a href=\"";
		s<<url;
		s<<"\" >";
		s<<DDataItem::protectXML(caption);
		s<<"</a>\n";
		s<<"</p>\n";
	}
}

void outputComment(DDataItem* item, QTextStream & s)
{
	if (item->m_comment.length()>0)
		s<<"<!--"<<item->m_comment<<"-->\n";
}

void printItem(DDataItem* item, QTextStream & s)
{
	s<<cleanHTML(item->m_text);

	outputPixParagraph(item, s);
	outputLinks(item, s);
	outputComment(item, s);
}

void kdisshtmldoc::writeItem(DDataItem* item, QTextStream & s, int level)
{
	DGenerator::writeItem(item, s, level);

	if (level == 0)
	{
		s<<cleanHTML(item->m_text)<<"\n";
		for (unsigned int i = 0; i<item->countChildren(); i++)
		{
			writeItem((DDataItem*) m_data->Item(item->childNum(i)), s, level+1);
		}
	}
	else if (level == 1)
	{
		m_cnt_lev1++;
		m_cnt_lev2=0;

		s<<"<hr>"<<endl;
		s<<"<h2>"<<m_cnt_lev1<<" "<<DDataItem::protectXML(item->m_summary)<<"</h2>\n\n";
		printItem(item, s);

		for (unsigned int i = 0; i<item->countChildren(); i++)
		{
			writeItem((DDataItem*) m_data->Item(item->childNum(i)), s, level+1);
		}
	}
	else if (level == 2)
	{
		m_cnt_lev2++;
		m_cnt_lev3=0;
		s<<"<h3>"<<m_cnt_lev1<<"."<<m_cnt_lev2<<" "<<DDataItem::protectXML(item->m_summary)<<"</h3>\n\n";
		printItem(item, s);

		for (unsigned int i = 0; i<item->countChildren(); i++)
		{
			writeItem((DDataItem*) m_data->Item(item->childNum(i)), s, level+1);
		}
	}
	else if (level == 3)
	{
		m_cnt_lev3++;
		s<<"<h4>"<<m_cnt_lev1<<"."<<m_cnt_lev2<<"."<<m_cnt_lev3<<" "<<DDataItem::protectXML(item->m_summary)<<"</h4>\n\n";
		printItem(item, s);

		s<<"<ol>\n";
		for (unsigned int i = 0; i<item->countChildren(); i++)
		{
			s<<"<li>\n";
			writeItem((DDataItem*) m_data->Item(item->childNum(i)), s, level+1);
			s<<"</li>\n";
		}
		s<<"</ol>\n";
	}
	else if (level > 3)
	{
		s<<"<b>"<<DDataItem::protectXML(item->m_summary)<<"</b><br />\n\n";
		printItem(item, s);

		s<<"<ul>\n";
		for (unsigned int i = 0; i<item->countChildren(); i++)
		{
			s<<"<li>\n";
			writeItem((DDataItem*) m_data->Item(item->childNum(i)), s, level+1);
			s<<"</li>\n";
		}
		s<<"</ul>\n";
	}
}

bool kdisshtmldoc::writeMaindoc(DDataItem *root, const QString & path)
{
	QFile textfile(path+"/main.html");
	if (!textfile.open(IO_WriteOnly | IO_Append) )
	{
		kdWarning()<<"could not open html file for append :-/"<<endl;
		return false;
	}

	QTextStream u(&textfile);
	if (Settings::templatesUTF8())
	{
		u.setEncoding(QTextStream::UnicodeUTF8);
	}

	// html header
	u<<"<html>\n";
	u<<"<head>\n";
	u<<"<title>"<<DDataItem::protectXML(root->m_summary)<<"</title>\n";

	if (Settings::templatesUTF8())
	{
		u<<"<meta http-equiv=Content-Type content=\"text/html;charset=UTF-8\">\n";
	}
	else
	{
		u<<"<meta http-equiv=Content-Type content=\"text/html;charset=";
		QString str = QTextCodec::codecForLocale()->name();
		u<<str.replace(" ", "-")<<"\">\n";
	}
	u<<"<link href=\"def.css\" rel=\"stylesheet\" type=\"text/css\" />\n";
	u<<"</head>\n<body>\n\n";

	// get the author name
	u<<"<h1>"<<DDataItem::protectXML(root->m_summary)<<"</h1>\n";
        if (!m_data->m_company.isEmpty())
        {
          u<<"<div class=\"company\">"<<DDataItem::protectXML(m_data->m_company)<<"</div>";
        }
        if (!m_data->m_email.isEmpty())
        {
          u<<"<div align=\"right\"><small><a href=\"mailto:"<<DDataItem::protectXML(m_data->m_email)<<"\">"<<DDataItem::protectXML(m_data->m_fname)<<" "<<DDataItem::protectXML(m_data->m_sname)<<" ("<<DDataItem::protectXML(m_data->m_email)<<")</a></small></div>";
        }
        else
        {
          u<<"<div align=\"right\"><small>"<<DDataItem::protectXML(m_data->m_fname)<<" "<<DDataItem::protectXML(m_data->m_sname)<<"</small></div>";
        }

	outputPixParagraph(root, u);
	outputLinks(root, u);
	outputComment(root, u);

	// now the central part, with text, pictures, etc ..
	writeItem(root, u, 0);

	// central part is finished
	u<<"</body>\n</html>\n";
	textfile.close();

	notifyDocGenerated( path+"/main.html" );

	return true;
}

#include "kdisshtmldoc.moc"
