/***************************************************************************
 *   Copyright (C) 2006-2008 by Ian Reinhart Geiser                        *
 *   geiseri@yahoo.com                                                     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   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.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


#include "wikiexport.h"
#include "ui_wikiexport.h"
#include "mindmap.h"
#include "block.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QFileDialog>

WikiExport::WikiExport(QWidget* parent, Qt::WFlags fl)
: QDialog( parent, fl ), m_ui( new Ui::WikiExport )
{
	m_ui->setupUi(this);
}

WikiExport::~WikiExport()
{
	delete m_ui;
}

void WikiExport::exportMindmap(MindMap * map)
{
	WikiExport dlg( QApplication::activeWindow() );
	dlg.m_ui->directorySelection->setText( map->getProperty("wiki.path",
		map->generateFilePath("wiki")).toString() );
	dlg.m_ui->formatSelector->setCurrentIndex( map->getProperty("wiki.format", 0  ).toInt() );

	if( dlg.exec() == QDialog::Rejected)
		return;

	if( dlg.m_ui->directorySelection->text().isEmpty() )
		return;

	map->setProperty("wiki.path", dlg.m_ui->directorySelection->text());
	map->setProperty("wiki.format", dlg.m_ui->formatSelector->currentIndex() );

 	map->setModified(true);

	QFile exportFile( dlg.m_ui->directorySelection->text());
	if( exportFile.open(QIODevice::WriteOnly) )
	{
		QTextStream ts(&exportFile);
		QFileInfo(exportFile).absoluteDir().path();
		dlg.dumpWikiMarkup( map->root(), &ts, dlg.m_ui->formatSelector->currentIndex() );
	}
	else
	{
		QMessageBox::critical(&dlg, "Error", QString("Could not save file."), QMessageBox::Ok, QMessageBox::NoButton);
	}
	exportFile.close();

}

void WikiExport::on_directorySelector_clicked()
{
	QString fileName = QFileDialog::getOpenFileName(this, tr("Select export file"),
                                                 m_ui->directorySelection->text(),
                                                 tr("Wiki Pages (*.wiki)"));
	if( !fileName.isEmpty() )
		m_ui->directorySelection->setText( fileName );
}

QString pad( const QChar &ch, int count )
{
	QString buffer;
	for( int idx = 0; idx < count; ++idx )
		buffer += ch;
	return buffer;
}

void WikiExport::dumpWikiMarkup(Block * block, QTextStream * ts, int format )
{
/** creole
* = Root node =
* == First Child ==
* === Second Child ===
* ==== Third Child ====
* ===== Fourth Child =====
* # Fifth Child
* ## Sixth Child
* ### Seventh Child
* #### Eighth Child
* ##### Nineth Child
* {{emblem.png}}
* text
*/

/** trac
* = Root node =
* == First Child ==
* === Second Child ===
* ==== Third Child ====
* ===== Fourth Child =====
* 1. Fifth Child
*  1. Sixth Child
*   1. Seventh Child
*    1. Eighth Child
*     1. Nineth Child
* [[Image(emblem.png)]]
* text
*/

/** parse wiki
* = Root node =
* == First Child ==
* === Second Child ===
* ==== Third Child ====
* ===== Fourth Child =====
* # Fifth Child
* ## Sixth Child
* ### Seventh Child
* #### Eighth Child
* ##### Nineth Child
* [emblem.png]
* text
*/

/** mediawiki
* = Root node =
* == First Child ==
* === Second Child ===
* ==== Third Child ====
* ===== Fourth Child =====
* # Fifth Child
* ## Sixth Child
* ### Seventh Child
* #### Eighth Child
* ##### Nineth Child
* [[emblem.png]]
* text
*/

	int size = block->path().size();

	switch( size )
	{
		case 0:
		case 1:
		case 2:
		case 3:
		case 4:
		{
			(*ts) << pad('=', size + 1 );
			(*ts) << " " << block->title().trimmed() << " ";
			if( format == MediaWiki || format == ParseWiki || format == Trac )
				(*ts) << pad('=', size + 1);
			(*ts) << "\n";
			if( !block->text().isEmpty() )
				(*ts) << block->text() << "\n\n";
			break;
		}
		case 5:
		case 6:
		case 7:
		case 8:
		case 9:
		{
			if( format == Creole || format == ParseWiki || format == MediaWiki )
				(*ts) <<  pad('#', size - 4);
			else if( format == Trac )
				(*ts) <<  pad(' ', size - 4) << " 1.";
			(*ts) << " " << block->title().trimmed() << " ";
			(*ts) << "\n";
			if( !block->text().isEmpty() )
				foreach( QString line, block->text().split("\n") )
				{
					if( format == Creole || format == ParseWiki || format == MediaWiki )
						(*ts) <<  pad('*', size - 3);
					else if( format == Trac )
						(*ts) <<  pad(' ', size - 3) << " *";
					(*ts) << " " << line << "\n";
				}
			break;
		}
		break;

		default:
			return;
		break;
	};
	// Print emblem
	//TODO: export image.
	if( format == MediaWiki )
	{
	// [[Image:Wiki.png|thumb|Caption text]]
	}
	else if( format == Trac )
	{
	// Image(Wiki.png Caption text)
	}
	else if( format == Creole )
	{
	// {{Wiki.png}}
	}
	else if( format == ParseWiki )
	{
	// [Wiki.png]
	}
	
	foreach( Block *block, block->children() )
		dumpWikiMarkup( block, ts, format );
}

