/***************************************************************************
                    firstrun.ui.h - Apollon First Run Wizard
                             -------------------
   begin       : September  2003
   copyright   : (C) 2003 by Arend van Beelen jr., 2004 by Martin Koebele
   email       : arend@auton.nl, apollon@mkoebele.de
 ***************************************************************************/

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

#include <cstdlib>

#include <libgift/libgift.h>
#include <libgift/conf.h>

#include <qapplication.h> 
#include <qdir.h>

#include <qregexp.h>
#include <qstringlist.h>

#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <kurl.h>



#include "apollonutils.h"

void FirstRunWizard::init()
{
	m_loader = KGlobal::iconLoader();
	browseButton->setPixmap(m_loader->loadIcon("folder", KIcon::Small, 16));
}

bool FirstRunWizard::checkFirstRun()
{
    	QString home(getenv("HOME"));
	if(QFile::exists(home + "/.giFT/giftd.conf"))
		return true;
	else 
	{
		
		//where are the plugins installed?
		QDir installedPath ("/usr/share/giFT/giftd.conf.template");
		if (QFile::exists(installedPath.path())) {
			installedPath = "/usr/share/giFT/";
		}
		else {
			installedPath = "/usr/local/share/giFT/giftd.conf.template";
			if (QFile::exists(installedPath.path()))
				installedPath = "/usr/local/share/giFT";
			else {
				KMessageBox::sorry(this, 
						i18n("Sorry, I couldn't locate your giFT installation,"
						"please select the path to your giFT like /.../share/giFT"),
						i18n("Where is your giFT?"));
				KFileDialog dialog(QString::null, QString("*"), this, "dirselect", true, 0);
				dialog.setMode(KFile::Directory);
				installedPath.setPath(dialog.getExistingDirectory());
				if (installedPath.path().isEmpty()) {
					KMessageBox::sorry(this, i18n("You didn't set a path to your "
						"installed giFT. We cannot proceed until this path is set. "
						"Alternatively, you can run gift-setup on a console. "
						"The installation will be aborted now."), i18n("No path set"));
					QApplication::exit();
				}
			}
		}
		
		
		
		
		int     result;

		setBackEnabled(page(0), false);
		setFinishEnabled(page(0), true);
		setHelpEnabled(page(0), false);

		if((result = exec()) == false)
			return false;

		// create a shared folder on the user's desktop if he wanted
		QDir dir;
		QFile file;
		QString sharedFolder;
		if(createRadio->isChecked())
		{
			sharedFolder = home + "/Desktop/" + i18n("Shared Folder");
			dir.mkdir(sharedFolder);
			file.setName(sharedFolder + "/.directory");
			file.open(IO_WriteOnly | IO_Truncate);
			QString contents("[Desktop Entry]\nIcon=folder_apollon\n");
			file.writeBlock(contents.latin1(), contents.length());
			file.close();
		}
		else
			sharedFolder = sharedFolderURL->text();

		
		QStringList subdirs = installedPath.entryList(QDir::Dirs);
		//remove the "." and ".."
		subdirs.pop_front();
		subdirs.pop_front();
		// install the giFT configuration templates
		QStringList lines;
		QString line;
		dir.mkdir(home + "/.giFT");
		file.setName(home + "/.giFT/giftd.conf");
		QString filename = installedPath.path() + "/giftd.conf.template";
		if(ApollonUtils::readFile(filename, lines) &&
		   file.open(IO_WriteOnly | IO_Truncate))
		{
			QValueListIterator<QString> it = lines.begin();
			while(it != lines.end())
			{
				if (lines[0].left(8) == "setup = ")
					line = "setup = 1 \n";
				else if(lines[0].left(11) == "incoming = ") {
					if (sharedFolder.isEmpty())
						line = "incoming = " + home + "/.giFT/incoming \n";
				        else
						line = "incoming = " + sharedFolder + "\n";
				}
								
				else if(lines[0].left(12) == "completed = ") {
					if (sharedFolder.isEmpty())
						line = "incoming = " + home + "/.giFT/completed \n";
				        else
						line = "completed = " + sharedFolder + "\n";
				}
					
				else if (lines[0].left(10) == "plugins = ") {
					QStringList plugins = subdirs;
					plugins.remove("ui");
					line = "plugins = " + plugins.join(":");
				}
					
				else
					line = lines[0];
				
				file.writeBlock(line.latin1(), line.length());
				it = lines.erase(it);
			}
			file.close();
		}

		//find all subdirs.
		
		for(QStringList::iterator it = subdirs.begin(); it != subdirs.end(); it++){
			QString pluginName = (*it);
	
			system("cp -r " + installedPath.path() +"/" + pluginName + " " + home + "/.giFT/.");
			
			if (pluginName == "OpenFT" || pluginName == "FastTrack") {
			
				file.setName(home + "/.giFT/" + pluginName + "/" + pluginName + ".conf");
				filename = home + "/.giFT/" + pluginName + "/" + pluginName + ".conf.template";
				if(ApollonUtils::readFile(filename, lines) &&
							       file.open(IO_WriteOnly | IO_Truncate))
				{
					QValueListIterator<QString> it = lines.begin();
					while(it != lines.end())
					{
						if(lines[0].left(7) == "alias =")
							line = "alias = " + userEdit->text() + " \n";
						else
							line = lines[0];
						file.writeBlock(line.latin1(), line.length());
						it = lines.erase(it);
					}
					file.close();
				}
			}
			else {
				QDir temp;
				temp.rename(home + "/.giFT/"+ pluginName + "/" + pluginName + ".conf.template",
					    home + "/.giFT/"+ pluginName + "/" + pluginName + ".conf");
			}
			
		}
		
		
	}
	return true;
}


void FirstRunWizard::browseButtonClick()
{
	KFileDialog dialog(sharedFolderURL->text(), QString("*"), this, "dirselect", true, 0);
	dialog.setMode(KFile::Directory);
	KURL url = dialog.getExistingDirectory();
	if(!url.isEmpty())
	{
		sharedFolderURL->setText(url.path());
		selectRadio->setChecked(true);
	}
}
