/***************************************************************************
 *   Copyright (C) 2007 by Muylkens Toon   *
 *   toon.muylkens@student.kuleuven.be   *
 *                                                                         *
 *   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 "Configuration.h"
//  #include <stdio.h>
//  #include <iostream>
//   using namespace std;

Configuration::Configuration(QWidget *parent)
     : QWidget(parent)
 {
     	ui.setupUi(this);
	ui.progressSpinBox->setMaximum(999);
	ui.progressSpinBox->setMinimum(2);
	loadSettings();
	QObject::connect(ui.cancelButton,SIGNAL(pressed()),this, SLOT(cancel()));
	QObject::connect(ui.okButton,SIGNAL(pressed()),this, SLOT(save()));
	QObject::connect(ui.deleteButton,SIGNAL(pressed()),this, SLOT(deleteProfile()));
	QObject::connect(ui.importButton,SIGNAL(pressed()),this, SLOT(importProfile()));
	QObject::connect(ui.fileDialogButton,SIGNAL(pressed()),this, SLOT(openFileDialog()));
	ui.passwordEdit->setEchoMode(QLineEdit::Password);
}

/**
 * we load the settings from the qtrainer config file (not the profile!!)
 */
void Configuration::loadSettings()
{
	///NetworkTab
	QSettings settings("ToonSoft", "Qtrainer");
	settings.beginGroup("ProgramSettings");
	ui.forumEdit->setText(settings.value("ForumURL").toString());
	ui.urlEdit->setText(settings.value("DatabaseURL").toString());
	ui.nameEdit->setText(settings.value("DatabaseName").toString());
	ui.portEdit->setText(settings.value("DatabasePort").toString());
	ui.usernameEdit->setText(settings.value("DatabaseUsername").toString());
	ui.passwordEdit->setText(settings.value("DatabasePassword").toString());
	ui.passwordEdit->setText(settings.value("DatabasePassword").toString());
	settings.endGroup();
	
	///ProfileTab
	settings.beginGroup("ProgramSettings");
	QString allprofiles=(settings.value("Profiles")).toString();
     	settings.endGroup();
	///append them all to the list.
	int i=1;
	while((allprofiles.section('!',i,i)).size()>0)
	{
		QListWidgetItem *SettingsItem = new QListWidgetItem(allprofiles.section('!', i, i),ui.listWidget);
		i++;
	}
	///profile-path
	settings.beginGroup("ProgramSettings");
	QString profilePath=(settings.value("Profile_Path")).toString();
     	settings.endGroup();
	ui.pathEdit->setText(profilePath);

	///AutloLogin
	settings.beginGroup("ProgramSettings");
	QString disabled = tr("No Autologin");
	QString allProfiles=(settings.value("Profiles")).toString();
	QString ProfileName=settings.value("AutoLogin").toString();
	if(ProfileName.size()==0){ProfileName=disabled;}
     	settings.endGroup();
	///append them all to the list.
	ui.autoLoginComboBox->addItem(disabled);
	int j=1;
	while((allProfiles.section('!',j,j)).size()>0)
	{
		ui.autoLoginComboBox->addItem(allProfiles.section('!', j, j));
		j++;
	}
	selectAutoLogin(ProfileName);

	
	///InformationTab
	settings.beginGroup("ProgramSettings");
	if(settings.value("ShowProgress").toString()=="true"){ui.progressCheckBox->setChecked(true);}
	else { ui.progressCheckBox->setChecked(false);}
	QString numberstring = settings.value("NumberOfProgressPoints").toString();
	int numberint= numberstring.toInt();
	ui.progressSpinBox->setValue(numberint);
	settings.endGroup();
	
}


/**
*This function select the index with the text: 'selection' or otherwise 'No Autologin'
*/
void Configuration::selectAutoLogin(QString selection){
int row=0;
for(int i=0;i<ui.autoLoginComboBox->count();i++){
	if(ui.autoLoginComboBox->itemText(i) == selection){row=i;}
	}
ui.autoLoginComboBox->setCurrentIndex(row);
}


/**
 * slot called when pressing cancel. We Don't save the settings and close the widget.
 */
void Configuration::cancel()
{
this->close();
}

/**
 * slot called when pressing OK. We save the settings and close the widget.
 */
void Configuration::save()
{	
	///NetworkTab
	QSettings settings("ToonSoft", "Qtrainer");
	settings.beginGroup("ProgramSettings");
	settings.setValue("ForumURL", ui.forumEdit->text());
	settings.setValue("DatabaseURL", ui.urlEdit->text());
	settings.setValue("DatabaseName", ui.nameEdit->text());
	settings.setValue("DatabasePort", ui.portEdit->text());
	settings.setValue("DatabaseUsername", ui.usernameEdit->text());
	settings.setValue("DatabasePassword", ui.passwordEdit->text());
 	settings.endGroup();

	///ProfileTab
	settings.beginGroup("ProgramSettings");
	QString newlist;
	for(int i=0;i<ui.listWidget->count();i++)
	{
	newlist.append("!"+ui.listWidget->item(i)->text()); 
	}
     	settings.setValue("Profiles", newlist);
	deleteProfilesFromDisk();
	importsProfilesForReal();
	if(isValidPath(ui.pathEdit->text())){
	copyProfilesToNewDir();
	settings.setValue("Profile_Path", ui.pathEdit->text());	}
	if(!isValidPath(ui.pathEdit->text())){
	notAValidPath();
	}

     	settings.endGroup();
	
	///AutloLogin
	settings.beginGroup("ProgramSettings");
	settings.setValue("AutoLogin", ui.autoLoginComboBox->currentText());
	settings.endGroup();

	///InformationTab
	settings.beginGroup("ProgramSettings");
	QString string ="";
	string.setNum(ui.progressSpinBox->value());
	settings.setValue("NumberOfProgressPoints", string);
	if(ui.progressCheckBox->isChecked()){string="true";}
	else {string="false";}
	settings.setValue("ShowProgress",string);
	settings.endGroup();
	if(isValidPath(ui.pathEdit->text())){emit configurationDialogClosed(); this->close(); }
	///tell Qtrainer we saved some configurations...maybe some actions need to be taken
}



/**
 * Deletes the current selected profile but doesn't commit it yet!
 */
void Configuration::deleteProfile()
{
int a =ui.listWidget->currentRow();
profilesToBeDeleted.append(ui.listWidget->item(a)->text());
ui.listWidget->takeItem(a);
}


/**
 * Import profiles tot the list, but don't commit yet!
 */
void Configuration::importProfile()
{
QString pathandfilename = QFileDialog::getOpenFileName(this, tr("Import Profile"),
                                                 QDir::homePath());

		QString profilename = getProfileNameFromPath(pathandfilename);

		///current profiles
		QString currentprofiles;
		QSettings settings("ToonSoft", "Qtrainer");
		settings.beginGroup("ProgramSettings");
		currentprofiles = settings.value("Profiles","").toString();
		settings.endGroup();

		///parcing
		int nbProfiles= currentprofiles.count("!");
		QStringList currentProfiles;
		for(int i=1;i<nbProfiles+1;i++){
		currentProfiles<<currentprofiles.section('!', i, i);
		}

		///legal
		if(pathandfilename.size()!=0 && pathandfilename.contains("QProfile",Qt::CaseSensitive) && !currentProfiles.contains(profilename)){
		profilesToBeImported.append(pathandfilename);
		ui.listWidget->addItem(profilename);
		}

		///not legal
		if(pathandfilename.size()!=0 && !pathandfilename.contains("QProfile",Qt::CaseSensitive)){
		QMessageBox::critical(this, tr("Qtrainer"),
                   tr("Not a valid QProfile"),
                   QMessageBox::Ok);
		}

		///also not legal
		if(pathandfilename.size()!=0 && currentProfiles.contains(profilename)){
		QMessageBox::critical(this, tr("Qtrainer"),
                   tr("Profile already in the list"),
                   QMessageBox::Ok);
		}

		///also not legal
		if(pathandfilename.size()!=0 && profilename.contains("!")){
		QMessageBox::critical(this, tr("Qtrainer"),
                   tr("Profilename may not contain '!'"),
                   QMessageBox::Ok);
		}
		
}


/**
 * extract name out of pathandfilename
 */
QString Configuration::getProfileNameFromPath(QString path)
{
		QStringList templist;
		templist = path.split("/");
		QString profilename = templist.at(templist.size()-1).section('.', 0, 0);
return profilename;
}

/**
 * Deletes the removes profiles from disk when saving.
 */
void Configuration::deleteProfilesFromDisk(){
	QSettings settings("ToonSoft", "Qtrainer");
	settings.beginGroup("ProgramSettings");
	QString profilePath=(settings.value("Profile_Path")).toString();
     	settings.endGroup();

for(int i =0;i<profilesToBeDeleted.size();i++)
{
profilePath.append("/");
QString file = profilesToBeDeleted.at(i);
emit profileDeletedFromDisk(file);
file.append(".QProfile");
//Q3UrlOperator *myOperator = new Q3UrlOperator(profilePath);
//myOperator->remove(file);
QDir::setCurrent(profilePath);
QFile(file).remove();
file.append("~");
QFile(file).remove();
///When we are deleting the current profile: log-out
}
}


/**
 * After committing the profiles are really coppied and imported
 */
void Configuration::importsProfilesForReal()
{
QString profilename="";
QString temp="";
QString destination="";
for(int i=0;i<profilesToBeImported.size();i++){
	///set profilename and destination
	QString profilename=getProfileNameFromPath(profilesToBeImported.at(i));
	QSettings settings("ToonSoft", "Qtrainer");
	settings.beginGroup("ProgramSettings");
	destination=(settings.value("Profile_Path")).toString();
	settings.endGroup();
	destination.append(profilename);
	destination.append(".QProfile");	
	
	///add to the config/settings file
// 	settings.beginGroup("ProgramSettings");
// 	temp=(settings.value("Profiles")).toString();
// 	temp.append("!"+profilename);
// 	settings.setValue("Profiles",temp);
//      	settings.endGroup();
	
	///copy to the profiles location/path
	QFile::copy(profilesToBeImported.at(i),destination);
}
}


/**
 * Let the user select a new directory for storing Profiles
 */
void Configuration::openFileDialog()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                 QDir::homePath(),
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks);
ui.pathEdit->setText(dir);
}



/**
 * return true when path is a valid path
 * @param path 
 */
bool Configuration::isValidPath(QString path)
{
return (QDir(path).exists());
}

void Configuration::notAValidPath()
{
QMessageBox msgBox;
		msgBox.setIcon(QMessageBox::Warning);
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setText(tr("Not a valid Path!"));
		msgBox.setDetailedText(tr("Qtrainer needs a valid path for saving the Profiles."));
 		msgBox.exec();
}


/**
 * When we have selected a new dir. We ask the user is he wants to copy the old profiles to the new dir.
 */
void Configuration::copyProfilesToNewDir()
{
QSettings settings("ToonSoft", "Qtrainer");
settings.beginGroup("ProgramSettings");
QString oldProfilePath=(settings.value("Profile_Path")).toString();
QString allprofiles=(settings.value("Profiles")).toString();
settings.endGroup();
if(ui.pathEdit->text() != oldProfilePath){
QMessageBox msgBox;
		msgBox.setIcon(QMessageBox::Question);
		msgBox.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
		msgBox.setText(tr("Do you want Qtrainer to copy the profiles to the new directory? "));
		msgBox.setDetailedText(tr("If you do not copy the profiles, Qtrainer won't find them!"));
		switch (msgBox.exec()) 
			{
			case QMessageBox::Yes:
			//Q3UrlOperator *myOperator = new Q3UrlOperator();
			///move them all
			int i=1;
			while((allprofiles.section('!',i,i)).size()>0)
			{
			QString fileString;
			fileString=oldProfilePath;
			fileString.append("/");
			fileString.append(allprofiles.section('!', i, i));
			fileString.append(".QProfile");
			QFile file(fileString);
			QString destination = ui.pathEdit->text();
			destination.append("/");
			destination.append(allprofiles.section('!', i, i));
			destination.append(".QProfile");
			file.copy(destination);
			//myOperator->copy(file,ui.pathEdit->text(),false);
			i++;
			}
			break;
			 
 			}
}
}

