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

#include <kdebug.h>
#include <kurl.h>
#include <klibloader.h>
#include <kapplication.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>

#include "DGenerator.h"
#include "KDissert.h"
#include "DDataControl.h"

static const char description[] =
I18N_NOOP("A tool for document creation using mindmap trees");

static const char version[] = "1.0.6pre3";

static KCmdLineOptions options[] =
{
	{ "+[URL]", I18N_NOOP( "Document to open" ), 0 },
	{ "g <name>", "Generator name", 0 },
	{ "p <file>", "Destination folder", 0 },
	KCmdLineLastOption
};

int main(int argc, char **argv)
{
	KAboutData about("kdissert", I18N_NOOP("kdissert"), version, description,
			KAboutData::License_GPL, "(C) 2003, 2004, 2005 Thomas Nagy", 0, "http://www.kde-apps.org/content/show.php?content=12725", "tnagyemail-mail@yahoo.fr");
	about.addAuthor( "Thomas Nagy", 0, "tnagy2^8@yahoo.fr" );

	// warning, utf-8 char
	about.addCredit( "André Somers", "patches, ideas" );
	about.addCredit( "Julien Antille", "build system improvements - bksys" );

	KCmdLineArgs::init(argc, argv, &about);
	KCmdLineArgs::addCmdLineOptions(options);

	KApplication app;

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
	if (args->isSet("g"))
	{
		QStringList gennames;
		QCStringList ba = (QCStringList) args->getOptionList("g");
		for (int i=0; i<ba.size();i++) gennames += QString(ba[i]);

		QString folder = QDir::homeDirPath()+"/kdissert-generated/";
		if (args->isSet("p")) folder = args->getOption("p");

		KURL document = args->url(0);

		kdDebug()<<"The generators are        "<<gennames.join(" ")<<endl;
		kdDebug()<<"The destination folder is "<<folder<<endl;
		kdDebug()<<"The kdissert document is  "<<document<<endl;

		DDataControl *data = new DDataControl();
		data->loadFromFile( document, 0, 1 );

		QFileInfo fileinfo( folder );
		if (!fileinfo.isDir() || !fileinfo.isWritable() )
		{
			QDir dir(folder);
			if (! dir.mkdir(folder) )
			{
				kdFatal()<<"Cannot open the destination directory"<<endl;
			}
		}

		QString hash = QDate::currentDate().toString( Qt::ISODate );
		hash += "-";
		hash += QTime::currentTime().toString( Qt::ISODate );

		for (int i=0; i<gennames.size(); i++)
		{
			QString libname = QString("lib")+gennames[i];
			KLibFactory* factory = KLibLoader::self()->factory(libname);
			if (!factory) continue;

			QDir dir(folder + "/" + gennames[i]);
			QString dirname = dir.absPath();

			QFileInfo fileinfo( dirname );
			if (fileinfo.isDir())
			{
				dir.rename(dirname, dirname+"."+hash+".old");
			}
			
			DGenerator* generator = static_cast<DGenerator*> (factory->create(NULL, "", ""));
			generator->generate( dirname, data );

			while (generator->generating);
			delete generator;
		}

		KLibLoader::self()->cleanUp();
		return 0;
	}
	else if (args->isSet("p"))
	{
		args->usage();
		kdFatal()<<"No generator given"<<endl;
	}
	else // TODO : session management
	{
		// no session.. just start up normally
		KDissert *widget = new KDissert(KMdi::IDEAlMode);

		if (args->count() != 0) for (int i=0; i < args->count(); i++) widget->openURL( args->url( i ) );
		else widget->slotFileNew();

		widget->show();
		args->clear();

		return app.exec();
	}
}
