/***************************************************************************
 *   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 <kurl.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 "kdisspdflatexarticle.h"

K_EXPORT_COMPONENT_FACTORY(libkdisspdflatexarticle, kdisspdflatexarticleFactory) 
	QObject *kdisspdflatexarticleFactory::createObject (QObject *, const char *, const char *, const QStringList &) { return new kdisspdflatexarticle; }


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

const QString kdisspdflatexarticle::fullName()
{
	return i18n("LaTeX Article");
}

const QString kdisspdflatexarticle::group()
{
	return i18n("LaTeX");
}

const QString kdisspdflatexarticle::description()
{
	return i18n("This template generates a pdflatex article with headers, footers and a table of content. You will need LaTeX for creating the corresponding pdf document.");
}

const QString kdisspdflatexarticle::quickstart()
{
	return i18n( "Go into the directory created and run 'make'\n"
			"View the document created by running 'make view'\n"
			"Using a LaTeX tool such as Kile is recommended for editing the generated file main.tex");
}

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

	// TODO: check the maximum width of the picture
	s<<"\\begin{figure}[htbp]\n";
	s<<"\\begin{center}\n";
	s<<"\\includegraphics[width=14cm]{pics/pic-"<<QString::number(item->Id())<<"}\n";
	s<<"\\caption{\\footnotesize{"<<protectTex(item->m_piccaption)<<"}}\n";
	s<<"%"<<item->m_picurl<<"\n";
	s<<"\\end{center}\n";
	s<<"\\end{figure}\n\n";
}

void kdisspdflatexarticle::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;
		if (i > 0) s<<"\\\\\n";
		
		s<<protectTex(caption);
		s<<" \\url{";
		s<<url;
		s<<"}\n";
	}
}

void kdisspdflatexarticle::outputComment(DDataItem* item, QTextStream & s)
{
	if (item->m_comment.length()>0)
	{
		if (Settings::commentTex())
			s<<item->m_comment<<"\n";
		else
			s<<"\\footnote{"<<htmlToTex(item->m_comment)<<"}\n";
	}
}

void kdisspdflatexarticle::outputData(DDataItem* item, QTextStream & s)
{
	s<<htmlToTex(item->m_text);
	outputComment(item, s);
	s<<"\n\n";
	outputPixParagraph(item, s);
	outputLinks(item, s);
}

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

	switch (level)
	{
		case 0:
			// XXX what if the user put a picture or a url ref 
			// in the root ?

			// comment this text since it is out of the body text
			s<<"\n"<<commentTex( htmlToTex(item->m_text) )<<"\n";
			if (Settings::commentTex())
				s<<item->m_comment<<"\n";
			else
				s<<commentTex(item->m_comment)<<"\n";
			break;
		case 1:
			s<<"\\section{"<<protectTex(item->m_summary)<<"}\n\n";
			outputData(item, s);
			break;
		case 2:
			s<<"\\subsection{"<<protectTex(item->m_summary)<<"}\n%\n";
			outputData(item, s);
			break;
		case 3:
			s<<"  \\subsubsection{"<<protectTex(item->m_summary)<<"}\n%%\n";
			outputData(item, s);
			break;
		default:
			s<<protectTex(item->m_summary)<<"\n%%%\n";
			outputData(item, s);
			break;
	}	

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

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

	QTextStream u(&textfile);
	if (Settings::templatesUTF8())
	{
		u.setEncoding(QTextStream::UnicodeUTF8);
		u<<"\\usepackage{ucs}\n";
		u<<"\\usepackage[utf8]{inputenc}\n\n\n";
	}
	else
	{
		u<<"\\usepackage[latin1]{inputenc}\n\n\n";
	}

	// print the headers and footers
	u<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
	u<<"%document headers and footers\n";
	u<<"\\lhead{}\n";
	u<<"\\chead{}\n";
	u<<"\\rhead{}\n";
        if (!m_data->m_company.isEmpty())
        {
          u<<"\\lfoot{"<<protectTex(m_data->m_company)<<"}\n";
        }
        else
        {
          u<<"\\lfoot{"<<protectTex(m_data->m_fname)<<" "<<protectTex(m_data->m_sname)<<"}\n";
        }
	u<<"\\cfoot{\\thepage/\\pageref{LastPage}}\n";
	u<<"\\rfoot{ \\today } % -> \\rfoot{\\number\\month/\\number\\day/\\number\\year} \n";
	u<<"\\pagestyle{fancyplain}\n";
	u<<"\n\n\n";

	// make a nice title for the first page
	u<<"\\title{"<<protectTex(root->m_summary)<<"}\n";
	u<<"\\date{\\today}\n";
        if (!m_data->m_email.isEmpty())
        {
          u<<"\\author{"<<protectTex(m_data->m_fname)<<" "<<protectTex(m_data->m_sname)<<" \\\\ \\texttt{"<<protectTex(m_data->m_email)<<"}}\n";
        }
        else
        {
          u<<"\\author{"<<protectTex(m_data->m_fname)<<" "<<protectTex(m_data->m_sname)<<"}\n";
        }
        
	// standard headers
	u<<"\n";
	u<<"\\begin{document}\n";
	u<<"\\maketitle\n";
	u<<"\\tableofcontents\n";

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

	// central part is finished
	u<<"\\end{document}\n\n";
	textfile.close();

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

	return true;
}

#include "kdisspdflatexarticle.moc"
