#include <qfiledialog.h>
#include <qmessagebox.h>
#include <qprocess.h>

#include "exports.h"
#include "file.h"
#include "linkablemapobj.h"
#include "misc.h"
#include "mainwindow.h"
#include "warningdialog.h"
#include "xsltproc.h"

extern Main *mainWindow;
extern QDir vymBaseDir;


ExportBase::ExportBase()
{
	indentPerDepth="  ";
	// Create tmpdir
	tmpDir.setPath (makeUniqueDir("/tmp/vym-XXXXXX"));
}

ExportBase::~ExportBase()
{
	// Remove tmpdir
	removeDir (tmpDir);
}

void ExportBase::setDir(const QString &p)
{
	outputDir=p;
}

void ExportBase::setFile (const QString &p)
{
	outputFile=p;
}

void ExportBase::setMapCenter(MapCenterObj *mc)
{
	mapCenter=mc;
}

void ExportBase::setCaption (const QString &s)
{
	caption=s;
}

void ExportBase::addFilter(const QString &s)
{
	filter=s;
}

bool ExportBase::execDialog()
{
	if (mapCenter && mapCenter->getMapEditor())
	{
		QFileDialog *fd=new QFileDialog( mapCenter->getMapEditor(), caption);
		fd->addFilter (filter);
		fd->setCaption(caption);
		fd->setMode( QFileDialog::AnyFile );
		fd->show();

		if ( fd->exec() == QDialog::Accepted )
		{
			if (QFile (fd->selectedFile()).exists() )
			{
				QMessageBox mb( __VYM,
					QObject::tr("The file %1 exists already.\nDo you want to overwrite it?").arg(fd->selectedFile()), 
				QMessageBox::Warning,
				QMessageBox::Yes | QMessageBox::Default,
				QMessageBox::Cancel | QMessageBox::Escape,
				QMessageBox::NoButton );
				mb.setButtonText( QMessageBox::Yes, QObject::tr("Overwrite") );
				mb.setButtonText( QMessageBox::No, QObject::tr("Cancel"));
				ExportBase ex;
				switch( mb.exec() ) 
				{
					case QMessageBox::Yes:
						// save 
						break;;
					case QMessageBox::Cancel:
						// return, do nothing
						return false;
						break;
				}
			}
			outputFile=fd->selectedFile();
			return true;
		}
	}
	return false;
}

QString ExportBase::getSectionString(BranchObj *bostart)
{
	// Make prefix like "2.5.3" for "bo:2,bo:5,bo:3"
	QString r;
	BranchObj *bo=bostart;
	int depth=bo->getDepth();
	while (depth>0)
	{
		r=QString("%1").arg(1+bo->getNum(),0,10)+"." + r;
		bo=(BranchObj*)(bo->getParObj());
		depth=bo->getDepth();
	}	
	if (r.isEmpty())
		return r;
	else	
		return r + " ";
}


////////////////////////////////////////////////////////////////////////
void ExportASCII::doExport()
{
	QFile file (outputFile);
	if ( !file.open( IO_WriteOnly ) )
	{
		// FIXME experimental, testing
		qWarning ("ExportBase::exportXML  couldn't open "+outputFile);
		return;
	}
	QTextStream ts( &file );	// use LANG decoding here...

	// Main loop over all branches
	QString s;
	QString actIndent("");
	int i;
	uint j;
	BranchObj *bo;
	bo=mapCenter->first();
	while (bo) 
	{
		// Make indentstring
		for (i=0;i<bo->getDepth();i++) actIndent+= indentPerDepth;

		if (bo->getDepth()==0)
		{
			ts << (bo->getHeading()+ "\n");
			for (j=0;j<bo->getHeading().length();j++) ts<<"=";
			ts << "\n";
		} else 	if (bo->getDepth()==1)
			ts << ("\n"+getSectionString(bo) + bo->getHeading()+ "\n");
		else	if (bo->getDepth()==2)
			ts << (actIndent + " o " + bo->getHeading()+ "\n");
		else	
			ts << (actIndent + " - " + bo->getHeading()+ "\n");
		
		// If necessary, write note
		if (!bo->getNote().isEmpty())
		{
			s =bo->getNoteASCII();
			s=s.replace ("\n","\n"+actIndent);
			ts << (s+"\n\n");
		}
		bo=bo->next();
		actIndent="";
	}
	file.close();
}

////////////////////////////////////////////////////////////////////////
void ExportKDEBookmarks::doExport() 
{
	MapEditor *me=NULL;
	if (mapCenter) me=mapCenter->getMapEditor();
	if (me)
	{
		WarningDialog dia;
		dia.setCancelButton (true);
		dia.setText(QObject::tr("Exporting the %1 bookmarks will overwrite\nyour existing bookmarks file.").arg("KDE"));
		dia.setCaption(QObject::tr("Warning: Overwriting %1 bookmarks").arg("KDE"));
		dia.setShowAgainName("/vym/warnings/overwriteKDEBookmarks");
		if (dia.exec()==QDialog::Accepted)
		{
			me->exportXML(tmpDir.path());

			XSLTProc p;
			p.setInputFile (tmpDir.path()+"/"+me->getMapName()+".xml");
			p.setOutputFile (tmpDir.home().path()+"/.kde/share/apps/konqueror/bookmarks.xml");
			p.setXSLFile (vymBaseDir.path()+"/styles/vym2kdebookmarks.xsl");
			p.process();

			QString ub=vymBaseDir.path()+"/scripts/update-bookmarks";
			QProcess *proc = new QProcess( );
			proc->addArgument(ub);

			if ( !proc->start() ) 
			{
				QMessageBox::warning(0, 
					QObject::tr("Warning"),
					QObject::tr("Couldn't find script %1\nto notifiy Browsers of changed bookmarks.").arg(ub));
			}	


		}
	}

}

////////////////////////////////////////////////////////////////////////
void ExportFirefoxBookmarks::doExport() 
{
	MapEditor *me=NULL;
	if (mapCenter) me=mapCenter->getMapEditor();
	if (me)
	{
		WarningDialog dia;
		dia.setCancelButton (true);
		dia.setText(QObject::tr("Exporting the %1 bookmarks will overwrite\nyour existing bookmarks file.").arg("Firefox"));
		dia.setCaption(QObject::tr("Warning: Overwriting %1 bookmarks").arg("Firefox"));
		dia.setShowAgainName("/vym/warnings/overwriteImportBookmarks");
		if (dia.exec()==QDialog::Accepted)
		{
			me->exportXML(tmpDir.path());

/*
			XSLTProc p;
			p.setInputFile (tmpDir.path()+"/"+me->getMapName()+".xml");
			p.setOutputFile (tmpDir.home().path()+"/.kde/share/apps/konqueror/bookmarks.xml");
			p.setXSLFile (vymBaseDir.path()+"/styles/vym2kdebookmarks.xsl");
			p.process();

			QString ub=vymBaseDir.path()+"/scripts/update-bookmarks";
			QProcess *proc = new QProcess( );
			proc->addArgument(ub);

			if ( !proc->start() ) 
			{
				QMessageBox::warning(0, 
					QObject::tr("Warning"),
					QObject::tr("Couldn't find script %1\nto notifiy Browsers of changed bookmarks.").arg(ub));
			}	

*/

		}
	}
}

////////////////////////////////////////////////////////////////////////
void ExportTaskjuggler::doExport() 
{
	MapEditor *me=NULL;
	if (mapCenter) me=mapCenter->getMapEditor();
	if (me)
	{
		me->exportXML(tmpDir.path());
		//FIXME testing
		cout << "tmpDir="<<tmpDir.path()<<endl;

		XSLTProc p;
		p.setInputFile (tmpDir.path()+"/"+me->getMapName()+".xml");
		p.setOutputFile (outputFile);
		p.setXSLFile (vymBaseDir.path()+"/styles/vym2taskjuggler.xsl");
		p.process();
	}

}

////////////////////////////////////////////////////////////////////////
void ExportLaTeX::doExport() 
{
	// Exports a map to a LaTex file.  
	// This file needs to be included 
	// or inported into a LaTex document
	// it will not add a preamble, or anything 
	// that makes a full LaTex document.
  QFile file (outputFile);
  if ( !file.open( IO_WriteOnly ) ) {
	QMessageBox::critical (0,QObject::tr("Critical Export Error"),QObject::tr("Could not write %1").arg(outputFile));
	mainWindow->statusMessage(QString(QObject::tr("Export failed.")));
    return;
  }
  QTextStream ts( &file );	// use LANG decoding here...
  ts.setEncoding (QTextStream::UnicodeUTF8); // Force UTF8
  
  // Main loop over all branches
  QString s;
  // QString actIndent("");
  // int i;
  BranchObj *bo;
  bo=mapCenter->first();
  while (bo) {
	if (bo->getDepth()==0);
	else if (bo->getDepth()==1) {
	  ts << ("\\chapter{" + bo->getHeading()+ "}\n");
	}
	else if (bo->getDepth()==2) {
	  ts << ("\\section{" + bo->getHeading()+ "}\n");
	}
	else if (bo->getDepth()==3) {
	  ts << ("\\subsection{" + bo->getHeading()+ "}\n");
	}
	else if (bo->getDepth()==4) {
	  ts << ("\\subsubsection{" + bo->getHeading()+ "}\n");
	}
	else {
	  ts << ("\\paragraph*{" + bo->getHeading()+ "}\n");
	}
	
	// If necessary, write note
	if (!bo->getNote().isEmpty()) {
	  ts << (bo->getNoteASCII());
	  ts << ("\n");
	}
    bo=bo->next();
   }
  file.close();
}

////////////////////////////////////////////////////////////////////////
ExportOO::ExportOO()
{
	useSections=false;
}

ExportOO::~ExportOO()
{
}	

QString ExportOO::buildList (BranchObj *current)
{
    QString r;
    BranchObj *bo;

    uint i=0;
    bo=current->getFirstBranch();
    if (bo)
    {
        // Start list
        r+="<text:list text:style-name=\"vym-list\">\n";
        while (bo)
        {
			r+="<text:list-item><text:p >";
			r+=quotemeta(bo->getHeading());
			// If necessary, write note
			if (!bo->getNote().isEmpty())
				r+=bo->getNoteOpenDoc();
			r+="</text:p>";
			r+=buildList (bo);	// recursivly add deeper branches
			r+="</text:list-item>\n";
			i++;
			bo=current->getBranchNum(i);
        }
        r+="</text:list>\n";
    }
    return r;
}


void ExportOO::exportPresentation()
{
	QString allPages;

	// Insert new content
	content.replace ("<!-- INSERT TITLE -->",quotemeta(mapCenter->getHeading()));
	content.replace ("<!-- INSERT AUTHOR -->",quotemeta(mapCenter->getAuthor()));

	QString	onePage;
	QString list;
	
	BranchObj *sectionBO=mapCenter->getFirstBranch();
    int i=0;
	BranchObj *pagesBO;
    int j=0;

	// Walk sections
	while (sectionBO)
	{
		if (useSections)
		{
			// Add page with section title
			onePage=sectionTemplate;
			onePage.replace ("<!-- INSERT PAGE HEADING -->", quotemeta(sectionBO->getHeading() ) );
			allPages+=onePage;
		} else
		{
			i=-2;	// only use inner loop to 
			        // turn mainbranches into pages
			sectionBO=mapCenter;
		}

		// Walk mainpages
		pagesBO=sectionBO->getFirstBranch();
		j=0;
		while (pagesBO)
		{
			// Add page with list of items
			onePage=pageTemplate;
			onePage.replace ("<!-- INSERT PAGE HEADING -->", quotemeta (pagesBO->getHeading() ) );
			list=buildList (pagesBO);
			onePage.replace ("<!-- INSERT LIST -->", list);
			allPages+=onePage;
			j++;
			pagesBO=sectionBO->getBranchNum(j);
		}
		i++;
		sectionBO=mapCenter->getBranchNum(i);
	}
	
	content.replace ("<!-- INSERT PAGES -->",allPages);

	// Write modified content
	QFile f (contentFile);
    if ( !f.open( IO_WriteOnly ) ) 
	{
		QMessageBox::critical (0,QObject::tr("Critical Export Error"),QObject::tr("Could not write %1").arg(contentFile));
		mainWindow->statusMessage(QString(QObject::tr("Export failed.")));
		return;
    }

    QTextStream t( &f );
    t << content;
    f.close();

	// zip tmpdir to destination
	zipDir (tmpDir,outputFile);	
}

bool ExportOO::setConfigFile (const QString &cf)
{
	configFile=cf;
	int i=cf.findRev ("/");
	if (i>=0) configDir=cf.left(i);
	SimpleSettings set;
	set.readSettings(configFile);

	// set paths
	templateDir=configDir+"/"+set.readEntry ("Template");

	QDir d (templateDir);
	if (!d.exists())
	{
		QMessageBox::critical (0,QObject::tr("Critical Export Error"),QObject::tr("Check \"%1\" in\n%2").arg("Template="+set.readEntry ("Template")).arg(configFile));
		return false;

	}

	contentTemplateFile=templateDir+"content-template.xml";
	contentFile=tmpDir.path()+"/content.xml";
	pageTemplateFile=templateDir+"page-template.xml";
	sectionTemplateFile=templateDir+"section-template.xml";

	if (set.readEntry("useSections").contains("yes"))
		useSections=true;

	// Copy template to tmpdir
	system ("cp -r "+templateDir+"* "+tmpDir.path());

	// Read content-template
	if (!loadStringFromDisk (contentTemplateFile,content))
	{
		QMessageBox::critical (0,QObject::tr("Critical Export Error"),QObject::tr("Could not read %1").arg(contentTemplateFile));
		return false;
	}

	// Read page-template
	if (!loadStringFromDisk (pageTemplateFile,pageTemplate))
	{
		QMessageBox::critical (0,QObject::tr("Critical Export Error"),QObject::tr("Could not read %1").arg(pageTemplateFile));
		return false;
	}
	
	// Read section-template
	if (useSections && !loadStringFromDisk (sectionTemplateFile,sectionTemplate))
	{
		QMessageBox::critical (0,QObject::tr("Critical Export Error"),QObject::tr("Could not read %1").arg(sectionTemplateFile));
		return false;
	}
	return true;
}

