/***************************************************************************
 *   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 <qimage.h>

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

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

#include "kdissbeamerslides.h"

K_EXPORT_COMPONENT_FACTORY(libkdissbeamerslides, kdissbeamerslidesFactory) 
	QObject *kdissbeamerslidesFactory::createObject (QObject *, const char *, const char *, const QStringList &) { return new kdissbeamerslides; }


kdissbeamerslides::kdissbeamerslides() : DGenerator()
{
	m_data = NULL;
}

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

const QString kdissbeamerslides::fullName()
{
	return i18n("Beamer presentation");
}

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

const QString kdissbeamerslides::description()
{
	return i18n("This generator create a LaTeX presentation using Beamer. A minimum Beamer distribution is included for your convenience, but you may want to check the beamer website for installing the complete distribution on your system (http://latex-beamer.sourceforge.net), and consulting the documentation. Most of the output is commented and does not appear in the slides. You will have to work a bit on the tex file generated, but the results are worth the effort :)");
}

const QString kdissbeamerslides::quickstart()
{
	return i18n( "Go into the directory created and run 'make' to create a pdf file (to view use 'make viewpdf'\n"
			"Acrobat Reader (Adobe tool) may give more interesting results (fullscreen display)\n"
			"A postscript document can be generated by using the command 'make ps' (to wiew use 'make viewps')\n"
			"Using a LaTeX tool such as Kile is recommended for editing the generated file main.tex");
}

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

	// the output is commented
	s<<"% KDissert makes it easy for users and includes pictures (png, jpg) automatic:\n";
	s<<"\\begin{figure}[htbp]\n";
	s<<"  \\begin{center}\n";
	QImage picture((item->m_picurl).mid(7));
	if (((item->m_picurl).right(3)).upper() == "PNG")
	{
		s<<"    \\includegraphics["<<picture.width()<<"pt, bb= 0 0 "<<picture.width()<<" "<<picture.height()<<"]{pics/pic-"<<QString::number(item->Id())<<".png}\n";
	}
	else
	{
		s<<"    \\includegraphics["<<picture.width()<<"pt, bb= 0 0 "<<picture.width()<<" "<<picture.height()<<"]{pics/pic-"<<QString::number(item->Id())<<".jpg}\n";
	}
	s<<"    \\caption{\\footnotesize{"<<protectTex(item->m_piccaption)<<"}}\n";
	s<<"    "<<item->m_picurl<<"\n";
	s<<"  \\end{center}\n";
	s<<"\\end{figure}\n\n";
}

void kdissbeamerslides::outputURL(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;


		s<<commentTex(url)<<"\n";
		s<<commentTex(caption)<<"\n";
	}
}

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

void kdissbeamerslides::outputData(DDataItem* item, QTextStream & s)
{
	//kdWarning()<<"output data for "<<item<<endl;
	s<<commentTex( htmlToTex(item->m_text) )<<"\n\n";
	outputPixParagraph(item, s);
	outputURL(item, s);
	outputComment(item, s);
}

void kdissbeamerslides::writeCompleteSlide(DDataItem* item, QTextStream & s, int level)
{
	//kdWarning()<<"calling kdissbeamerslides::writeCompleteSlide "<<level<<" "<<item<<endl;
	if (level == 0)
	{
		s<<"%------------------------------------------------------------------- \n";
		s<<"\\begin{frame}\n";
		s<<"\\frametitle{"<<protectTex(item->m_summary)<<"}\n\n";

		if (item->countChildren() > 0)
		{	    
			s<<"\\begin{itemize}\n";
			outputData(item, s);

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

			s<<"\\end{itemize}\n";
		}
		else
		{
			outputData(item, s);
		}
		s<<"\\end{frame}\n";
		s<<"%------------------------------------------------------------------- \n";
	}
	else if (level == 1)
	{
		s<<"\\item "<<protectTex(item->m_summary)<<"\n%\n";
		outputData(item, s);

		if (item->countChildren() > 0)
		{
			s<<"\\begin{itemize}\n";
			for (unsigned int i = 0; i<item->countChildren(); i++)
			{
				writeCompleteSlide((DDataItem*) m_data->Item(item->childNum(i)), s, level+1);
			}
			s<<"\\end{itemize}\n";
		}
	}
	else if (level == 2)
	{
		s<<"\\item "<<protectTex(item->m_summary)<<"\n";
		outputData(item, s);

		if (item->countChildren() > 0)
		{
			s<<"\\begin{itemize}\n";
			for (unsigned int i = 0; i<item->countChildren(); i++)
			{
				writeCompleteSlide((DDataItem*) m_data->Item(item->childNum(i)), s, level+1);
			}
			s<<"\\end{itemize}\n";
		}
	}
	else if (level == 3)
	{
		s<<"\\item "<<protectTex(item->m_summary)<<"\n";
		outputData(item, s);

		for (unsigned int i = 0; i<item->countChildren(); i++)
		{
			writeCompleteSlide((DDataItem*) m_data->Item(item->childNum(i)), s, level+1);
		}
	}
	else if (level > 3)
	{
		// too much nesting, output in comments
		s<<commentTex(item->m_summary)<<"\n";
		outputData(item, s);

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

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

	if (level == 0)
	{
		if (! item->m_pix.isNull())
		{
			s<<"% you will have to convert the picture to .eps to make this work :\n";
			s<<"%\\Logo(2,5){\\includegraphics[width=1cm]{"<<QString::number(item->Id())<<".eps}}\n";
		}

		// comment this text since it is out of the body text
		s<<"\n"<<commentTex( htmlToTex(item->m_text) )<<"\n";
		outputURL(item, s);
		outputComment(item, s);
	}

	for (unsigned int i = 0; i<item->countChildren(); i++)
	{
		DDataItem* subtree = (DDataItem*) m_data->Item(item->childNum(i));

		// 10 is the maximum maximum size of a subtree 
		// that can fit on a single slide

		if (level == 0 && item->countChildren() >= 1)
		{
			s<<"\\section{"<<protectTex(subtree->m_summary)<<"}\n";
		}
		else if (level == 1 && item->countChildren() >= 1)
		{
			s<<"\\subsection{"<<protectTex(subtree->m_summary)<<"}\n";
		}

		if (subtree->countFamily() < 10)
		{
			writeCompleteSlide(subtree, s, 0);
		}

		else if (level == 0)
		{
			outputData(subtree, s);
			writeItem(subtree, s, level+1);
		}
		else if (level == 1)	
		{
			outputData(subtree, s);
			writeItem(subtree, s, level+1);
		}
		else
		{
			writeCompleteSlide(subtree, s, 0);
			kdWarning()<<i18n("Your mindmap is too huge")<<endl;
		}
	}
}

bool kdissbeamerslides::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";
	}

	// make a nice title for the first page
	u<<"\\title{"<<protectTex(root->m_summary)<<"}\n";
	u<<"\\date{\\today}\n";
	QString name(protectTex(m_data->m_fname)+" "+protectTex(m_data->m_sname));
	if (!m_data->m_email.isEmpty())
	{
		name+=" \\\\ \\texttt{"+protectTex(m_data->m_email)+"}";
	}
	if (m_data->m_company.isEmpty())
	{
		u<<"\\author{"<<name<<"}\n";
	}
	else
	{
		u<<"\\author{"<<protectTex(m_data->m_company)<<"}\n";
		u<<"\\institute{"<<name<<"}\n";
	}

	// standard headers
	u<<"\n";
	u<<"\\begin{document}\n";

	u<<"\\frame[plain]{\\titlepage}\n\n";

	u<<"%\\tableofcontents\n";
	u<<i18n("% tables of contents are generated from the \\section and \\subsection statements");
	u<<"\n";
	u<<i18n("% you may probably wish to insert them before the appropriate frames");
	u<<"\n\n\n";

	u<<"\\begin{frame}\n \\frametitle{Outline}\n \\tableofcontents\n \\end{frame} \n\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 "kdissbeamerslides.moc"
