/***************************************************************************
 *   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 "MainWindow.h"
//  #include <stdio.h>
// #include <iostream>
// using namespace std;


MainWindow::MainWindow(QWidget *parent)
     : QMainWindow(parent)
 {
	powertraining =false;
	body = false;
	loggedin=false;

	ui.setupUi(this);

	makeActions();

	ui.listWidget->hide();
	ui.menuProfile->setEnabled(false);
//	ui.vboxLayout->setContentsMargins (9,0,9,0 );
	
//	populatelistWidget(); ///left area in the MainWindow
	loadwidgets(); ///Now we should load the widgets but not show them yet!

	setMenuConnections();
	setToolBar();
		
	setUrls();///if no Database or forum url is set. Set the default one.

	///show open profile dialog on startup
	QSettings settings("ToonSoft", "Qtrainer");
	settings.beginGroup("ProgramSettings");
	if(settings.value("AutoLogin").toString()!=tr("No Autologin")){openproject(settings.value("AutoLogin").toString());}
	else if(settings.value("OpenExistingProfileOnStartup").toInt()==2){openproject();}
	settings.endGroup();
}

/**
*Sets all the connections related to the menu
*/
void MainWindow::setMenuConnections(){
QObject::connect(actionNew_Project, SIGNAL(triggered()), this, SLOT(newproject()));
QObject::connect(actionOpen_Existing_Project, SIGNAL(triggered()), this, SLOT(openproject()));
QObject::connect(actionConfigure_Qtrainer, SIGNAL(triggered()), this, SLOT(openConfigurationDialog()));
QObject::connect(actionAbout_Qtrainer, SIGNAL(triggered()), this, SLOT(openAboutDialog()));
QObject::connect(actionLogout, SIGNAL(triggered()), this, SLOT(logout()));
QObject::connect(actionExport, SIGNAL(triggered()), this, SLOT(exportProfile()));
QObject::connect(actionRecover_from_backup, SIGNAL(triggered()), this, SLOT(recoverProfile()));
QObject::connect(actionExit_Qtrainer, SIGNAL(triggered()), this, SLOT(close()));
	


}

/**
*Constructs all the actions needed by all the projects
*/
void MainWindow::makeActions(){
    actionNew_Project = new QAction(this);
    actionNew_Project->setObjectName(QString::fromUtf8("actionNew_Project"));
    actionNew_Project->setIcon(QIcon(QString::fromUtf8(":/planner/filenew.png")));
    actionOpen_Existing_Project = new QAction(this);
    actionOpen_Existing_Project->setObjectName(QString::fromUtf8("actionOpen_Existing_Project"));
    actionOpen_Existing_Project->setIcon(QIcon(QString::fromUtf8(":/planner/open.png")));
    actionExit_Qtrainer = new QAction(this);
    actionExit_Qtrainer->setObjectName(QString::fromUtf8("actionExit_Qtrainer"));
    actionExit_Qtrainer->setIcon(QIcon(QString::fromUtf8(":/planner/exit.png")));
    actionAbout_Qtrainer = new QAction(this);
    actionAbout_Qtrainer->setObjectName(QString::fromUtf8("actionAbout_Qtrainer"));
    actionConfigure_Qtrainer = new QAction(this);
    actionConfigure_Qtrainer->setObjectName(QString::fromUtf8("actionConfigure_Qtrainer"));
    actionConfigure_Qtrainer->setIcon(QIcon(QString::fromUtf8(":/planner/configure.png")));
    actionExport = new QAction(this);
    actionExport->setObjectName(QString::fromUtf8("actionExport"));
    actionExport->setIcon(QIcon(QString::fromUtf8(":/planner/fileexport.png")));
    actionExport_to_HTML = new QAction(this);
    actionExport_to_HTML->setObjectName(QString::fromUtf8("actionExport_to_HTML"));
    actionExport_to_HTML->setIcon(QIcon(QString::fromUtf8(":/planner/fileexport.png")));
    actionLogout = new QAction(this);
    actionLogout->setObjectName(QString::fromUtf8("actionLogout"));
    actionLogout->setIcon(QIcon(QString::fromUtf8(":/planner/logout.png")));
    actionRecover_from_backup = new QAction(this);
    actionRecover_from_backup->setObjectName(QString::fromUtf8("actionRecover_from_backup"));
    actionRecover_from_backup->setIcon(QIcon(QString::fromUtf8(":/planner/redo.png")));

	actionNew_Project->setText(QApplication::translate("MainWindow", "New Profile", 0, QApplication::UnicodeUTF8));
    actionOpen_Existing_Project->setText(QApplication::translate("MainWindow", "Open Existing Profile", 0, QApplication::UnicodeUTF8));
    actionExit_Qtrainer->setText(QApplication::translate("MainWindow", "Exit Qtrainer", 0, QApplication::UnicodeUTF8));
    actionAbout_Qtrainer->setText(QApplication::translate("MainWindow", "About Qtrainer", 0, QApplication::UnicodeUTF8));
    actionConfigure_Qtrainer->setText(QApplication::translate("MainWindow", "Configure Qtrainer", 0, QApplication::UnicodeUTF8));
    actionExport->setText(QApplication::translate("MainWindow", "Export", 0, QApplication::UnicodeUTF8));
    actionExport_to_HTML->setText(QApplication::translate("MainWindow", "Export to HTML", 0, QApplication::UnicodeUTF8));
    actionLogout->setText(QApplication::translate("MainWindow", "Logout", 0, QApplication::UnicodeUTF8));
    actionRecover_from_backup->setText(QApplication::translate("MainWindow", "Recover from backup", 0, QApplication::UnicodeUTF8));


	///menu actions:
	ui.menuHelp->addAction(actionAbout_Qtrainer);
  	ui.menuFile->addAction(actionNew_Project);
    	ui.menuFile->addAction(actionOpen_Existing_Project);
    	ui.menuFile->addSeparator();
    	ui.menuFile->addAction(actionExit_Qtrainer);
    	ui.menuPreferences->addAction(actionConfigure_Qtrainer);
    	ui.menuProfile->addAction(actionExport);
	ui.menuProfile->addAction(actionExport_to_HTML);
    	ui.menuProfile->addSeparator();
    	ui.menuProfile->addAction(actionRecover_from_backup);
    	ui.menuProfile->addSeparator();
    	ui.menuProfile->addAction(actionLogout);



}

/**
*Public SLot: This method sets the toolBar to logged-off position
*More precisely it sets the buttons that are alwayws show, when logged in in any project
*or when logged off
*/
void MainWindow::setToolBar(){
	ui.toolBar->clear();
	ui.toolBar->addAction(actionNew_Project);
    	ui.toolBar->addAction(actionOpen_Existing_Project);
	ui.toolBar->addAction(actionLogout);
	ui.toolBar->addAction(actionExit_Qtrainer);
}

/**
*We show the configuration dialog
*/
void MainWindow::openConfigurationDialog()
{
	Configuration *configDialog = new Configuration(0);
	configDialog->setWindowFlags(Qt::SubWindow);
	QObject::connect(configDialog,SIGNAL(configurationDialogClosed()),this, SLOT(configurationChanged()));
	QObject::connect(configDialog,SIGNAL(profileDeletedFromDisk(QString)),this, SLOT(profileDeletedFromDisk(QString)));
	configDialog->show();
}	

/**
* SLOT: accesed when a profile is being deleted. When it is the current profile that is being deleted
* we log out.
*/
void MainWindow::profileDeletedFromDisk(QString name)
{
	if(loggedin && powertraining && name==filehandlerPowerTraining->getprofilename()){
	logout();
	}
	if(loggedin && body && name==filehandlerBodyMeasurements->getprofilename()){
	logout();
	}
	qtrainerWelcomsWidget->populatelist();
	///TODO
}

/**
*makes sure we are loged out.
*/
void MainWindow::logout()
{
	if(loggedin){
	loggedin=false;
	if(powertraining){
		filehandlerPowerTraining->logout();
		powerTrainingMainWidget->logout();
		powerTrainingMainWidget->hide();
		}
	if(body){filehandlerBodyMeasurements->logout();
		bodyMeasurementsMainWidget->logout();
		bodyMeasurementsMainWidget->hide();
		}
	ui.menuProfile->setEnabled(false);
	
	ui.listWidget->setCurrentRow(0);
	ui.listWidget->setEnabled(false);
	ui.listWidget->hide();
	qtrainerWelcomsWidget->show();
	setToolBar();
	}
}

/**
*Opens the newprofile wizard
*/
void MainWindow::newproject()
{
	logout();
	NewProfileWizard *newprofilewizard = new NewProfileWizard(0);
	newprofilewizard->setWindowFlags(Qt::SubWindow); 
	QObject::connect(newprofilewizard,SIGNAL(finishedPowerTraining(ConfigFileHandlerPowerTraining*)),this, SLOT(loadNewPowerTraining(ConfigFileHandlerPowerTraining*)));
	QObject::connect(newprofilewizard,SIGNAL(finishedBodyMeasurements(ConfigFileHandlerBodyMeasurements*)),this, SLOT(loadNewBodyMeasurements(ConfigFileHandlerBodyMeasurements*)));
	newprofilewizard->show();
	QObject::connect(newprofilewizard,SIGNAL(finished()),qtrainerWelcomsWidget, SLOT(populatelist()));
}
	
/**
*This method opens the OPEN PROJECT DIALOG, in that dialog all the profiles, that are 
*stored in the Qtrainer ProfilePath
*/
void MainWindow::openproject()
{
	logout();
	openprofilewizard->show();
	openprofilewizard->setFocus(Qt::OtherFocusReason);
	openprofilewizard->activateWindow();
	openprofilewizard->raise();
}

/**
*This method opens the profile with name profilename
*when it is in the profilepath, otherwise it does nothing.
* @return true in case the profile was an existing one and was loaded.
*otherwise false
*/
bool MainWindow::openproject(QString profilename){
	bool profileExists=false;

	///read the necessarry settings
	QSettings settings("ToonSoft", "Qtrainer");
	settings.beginGroup("ProgramSettings");
	QString allprofiles=(settings.value("Profiles")).toString();
     	settings.endGroup();

	///check if the given profilename is an existing one
	int i=1;
	while((allprofiles.section('!',i,i)).size()>0 && !profileExists)
	{
		if(allprofiles.section('!', i, i)==profilename){
		profileExists=true;
		}
		i++;
	}
	if(profileExists) {
		logout();
		
		ConfigFileHandler *filehandler = new ConfigFileHandler(profilename);
		QString s = filehandler->getSport();
		if(s!=QString("PowerTraining") && s!=QString("BodyMeasurements")){
			return false;
			}
	
		if(s==QString("PowerTraining")){
			powertraining=true;
			body=false;
			ExerciseHandler *exercise = new ExerciseHandler(this);	
			filehandlerPowerTraining = new ConfigFileHandlerPowerTraining(profilename,exercise,this); 
			loadPowerTrainingWidget();
			}

		if(s==QString("BodyMeasurements")){
			powertraining=false;
			body=true;
			filehandlerBodyMeasurements = new ConfigFileHandlerBodyMeasurements(profilename, this);
// 			this->filehandlerBodyMeasurements->setprofilename(filehandler->getprofilename());
			loadBodyMeasurementWidget();
			}
	
		//loadnewproject();
		delete filehandler;
		return true;
		}
	return false;
}

/**
*Loads all the widgets for BodyMeasurements profided filehandlerBodyMeasurements points to a legal filehandler
*and powertraining ==false and body==true
*/
void MainWindow::loadBodyMeasurementWidget(){
ui.listWidget->show();
qtrainerWelcomsWidget->hide();
ui.menuProfile->setEnabled(true);
///setting current widget to 0=welcome+information
ui.listWidget->setCurrentRow(0); //used to be: setCurrentItem(InformationItem);


bodyMeasurementsMainWidget = new BodyMeasurementsMainWidget(filehandlerBodyMeasurements, ui.centralwidget, ui.listWidget, ui.toolBar);
QObject::connect(bodyMeasurementsMainWidget,SIGNAL(updateToolBar()),this,SLOT(setToolBar()));
/*QObject::connect(bodyMeasurementsMainWidget, SIGNAL(setToolBar(int)), this, SLOT(setToolBar(int)));
*/
ui.hboxLayout->addWidget(bodyMeasurementsMainWidget);	
QObject::connect(this,SIGNAL(resizeWidgets()),bodyMeasurementsMainWidget,SLOT(rescale()));
QObject::connect(ui.listWidget,SIGNAL(itemClicked(QListWidgetItem*)),bodyMeasurementsMainWidget,SLOT(itemhasbeenchanged(QListWidgetItem*)));
	
bodyMeasurementsMainWidget->loadsettings(filehandlerBodyMeasurements);
bodyMeasurementsMainWidget->login();
bodyMeasurementsMainWidget->show();	
ui.listWidget->setEnabled(true);
loggedin=true;
}


/**
*Loads all the widgets for PowerTraining profided filehandlerPowerTraining points to a legal filehandler
*and powertraining ==true and body==false
*/
void MainWindow::loadPowerTrainingWidget(){
ui.listWidget->show();
qtrainerWelcomsWidget->hide();
ui.menuProfile->setEnabled(true);
///setting current widget to 0=welcome+information
ui.listWidget->setCurrentRow(0); //used to be: setCurrentItem(InformationItem);

powerTrainingMainWidget = new PowerTrainingMainWidget(filehandlerPowerTraining, ui.centralwidget, ui.listWidget, ui.toolBar);
QObject::connect(powerTrainingMainWidget,SIGNAL(updateToolBar()),this,SLOT(setToolBar()));
///TODO Make it work by using QModelIndex: QObject::connect(powerTrainingMainWidget,SIGNAL(setCurrentIndexInLeftFrame(int)),ui.listWidget,SLOT(setCurrentIndex(int)));
/*QObject::connect(powerTrainingMainWidget, SIGNAL(setToolBar(int)), this, SLOT(setToolBar(int)));
*/ui.hboxLayout->addWidget(powerTrainingMainWidget);	
QObject::connect(this,SIGNAL(resizeWidgets()),powerTrainingMainWidget,SLOT(rescale()));
/*filehandlerPowerTraining->setprofilename(profilename);*/
QObject::connect(ui.listWidget,SIGNAL(itemClicked(QListWidgetItem*)),powerTrainingMainWidget,SLOT(itemhasbeenchanged(QListWidgetItem*)));

powerTrainingMainWidget->loadsettings(filehandlerPowerTraining);
powerTrainingMainWidget->login();
powerTrainingMainWidget->show();
ui.listWidget->setEnabled(true);
loggedin=true;
}


/**
*SLOT: filehandler is the new PowerTraining filehandler.
*/
void MainWindow::loadNewPowerTraining(ConfigFileHandlerPowerTraining *filehandler){
	filehandler->setParent(this);
	this->filehandlerPowerTraining = filehandler;
	loadPowerTrainingWidget();
// 	powertraining=true;
// 	body=false;
// 	loadnewproject();
}
	
/**
*SLOT: filehandler is the new Body Measurements filehandler.
*/
void MainWindow::loadNewBodyMeasurements(ConfigFileHandlerBodyMeasurements *filehandler){
	filehandler->setParent(this);
	this->filehandlerBodyMeasurements = filehandler;
	loadBodyMeasurementWidget();
///Some test stuff:
// 	BodyPart *part = new BodyPart("unit","objectname");
// 	part->setExplanation("uitleg");
// 	BodyMeasurement *mes = new BodyMeasurement(part, StringDate(QDate::currentDate()),23);
// 	filehandler->addBodyPart(part);
// 	part->linkMeasurement(mes);
///end

// 	powertraining=false;
// 	body=true;
// 	loadnewproject();
}

	/**
	*loads the profile set to the filehandler into the propper specific filehandler
	*When the type set in the filehandler is unknown, the function returns false
	*When the type is known the propper filehandler is made and setup, and the widgets are loaded.
	*/
// 	void MainWindow::loadnewproject()
// 	{
	///the information dialog
	///updateInformation(); is called when itemhasbeenchanged(InformationItem) is called

	///menu Profile
// 	ui.listWidget->show();
// 	qtrainerWelcomsWidget->hide();
// 	ui.menuProfile->setEnabled(true);
// 	///setting current widget to 0=welcome+information
// 	ui.listWidget->setCurrentRow(0); //used to be: setCurrentItem(InformationItem);
	//if(loggedin && powertraining){
		/*powerTrainingMainWidget->loadsettings(filehandlerPowerTraining);
		powerTrainingMainWidget->login();
		powerTrainingMainWidget->show();	*/	
// 		}
//	if(loggedin && body){
// 		bodyMeasurementsMainWidget->loadsettings(filehandlerBodyMeasurements);
// 		bodyMeasurementsMainWidget->login();
// 		bodyMeasurementsMainWidget->show();
// 		}
	
	//ui.listWidget->setEnabled(true);
	///Now we set up the signals-slots
// 	QObject::connect(ui.listWidget,SIGNAL(itemClicked(QListWidgetItem*)),powerTrainingMainWidget,SLOT(itemhasbeenchanged(QListWidgetItem*)));
// 	QObject::connect(ui.listWidget,SIGNAL(itemClicked(QListWidgetItem*)),bodyMeasurementsMainWidget,SLOT(itemhasbeenchanged(QListWidgetItem*)));
	
	
// 		if(body){
// 		ui.stackedWidget->insertWidget(1,plotwidget);
// 		ui.stackedWidget->insertWidget(2,addbodydatawidget);
// 		ui.stackedWidget->setCurrentIndex(0);
// 		addbodydatawidget->loadsettings(filehandlerBodyMeasurements);
// 		}
//	setLeftFrame();
//	loggedin=true;
// 	}

/**	QString MainWindow::getProfileLabel(){
		QString text;
		text=tr("ProfileName: ");
		if(powertraining){
			text.append(filehandlerPowerTraining->getprofilename());
			}
		if(body){
			text.append(filehandlerBodyMeasurements->getprofilename());
			}
		text.append(" (");
		if(powertraining){
			text.append(filehandlerPowerTraining->getSport());
			}
		if(body){
			text.append(filehandlerBodyMeasurements->getSport());
			}
		text.append(")");
		return text;
		
	}
*/

	/**
	*if no Database or forum url is set. Set the default one.
	*also the path is set to the default path when none is set.
	*the URLS are saved NOT in the profile but in the system settings
	*/	
	void MainWindow::setUrls(){
	QSettings settings("ToonSoft", "Qtrainer");
	settings.beginGroup("ProgramSettings");
	if(!settings.contains("ForumURL") || settings.value("ForumURL").toString().size()==0){settings.setValue("ForumURL","http://tuxer.ulyssis.be/qtrainer/forum/index.php");}
	if(!settings.contains("DatabaseURL") || settings.value("DatabaseURL").toString().size()==0){settings.setValue("DatabaseURL","http://tuxer.ulyssis.be:80/qtrainer/server.php");}
	settings.endGroup();

	///set Default profilePath when none is set (first time you run Qtrainer)
	settings.beginGroup("ProgramSettings");
	if(!settings.contains("Profile_Path") || settings.value("Profile_Path").toString().size()==0){
		QString dir=QDir::homePath();
		dir.append("/Qtrainer_Profiles/");
		QDir mydir;
		mydir.mkdir(dir);
		settings.setValue("Profile_Path",dir );
		}
	settings.endGroup();

	///set default for nbdatapointstouseforprogress
	settings.beginGroup("ProgramSettings");
	if(!settings.contains("ShowProgress")){
		settings.setValue("ShowProgress","true" );
		}
	if(!settings.contains("NumberOfProgressPoints")){
		settings.setValue("NumberOfProgressPoints","10" );
		}
	
	settings.endGroup();

	}



	
	
	///this is called when starting Qtrainer
	void MainWindow::loadwidgets()
	{
		///exercise for storing the exercises name and description
//		ExerciseHandler *exercise = new ExerciseHandler(this);	

		///for handling all the file reading and writing
//		filehandlerPowerTraining = new ConfigFileHandlerPowerTraining("default",exercise); 

//		exercise->setParent(filehandlerPowerTraining);
//		filehandlerPowerTraining->setParent(this);	///so it gets destroyed when this is destroyed
		/**we make this thing ones so we can connect the settings and don't need to remove
		signals/slots when a new profile is loaded, we just call filehandlerPowerTraining->setprofile();*/
		///must be executed first

//		filehandlerBodyMeasurements = new ConfigFileHandlerBodyMeasurements();
//		filehandlerBodyMeasurements->setParent(this);
		
		openprofilewizard = new OpenExistingProfile(0);
		openprofilewizard->setWindowFlags(Qt::SubWindow); 
		QObject::connect(openprofilewizard,SIGNAL(signalfinished(QString)),this, SLOT(openproject(QString)));
		openprofilewizard->hide();
	
// 		powerTrainingMainWidget = new PowerTrainingMainWidget(ui.centralwidget, ui.listWidget, ui.toolBar);
// 		QObject::connect(powerTrainingMainWidget,SIGNAL(updateToolBar()),this,SLOT(setToolBar()));
// 		///TODO Make it work by using QModelIndex: QObject::connect(powerTrainingMainWidget,SIGNAL(setCurrentIndexInLeftFrame(int)),ui.listWidget,SLOT(setCurrentIndex(int)));
// 		/*QObject::connect(powerTrainingMainWidget, SIGNAL(setToolBar(int)), this, SLOT(setToolBar(int)));
// 		*/ui.hboxLayout->addWidget(powerTrainingMainWidget);	
// 		powerTrainingMainWidget->hide();
	
// 		bodyMeasurementsMainWidget = new BodyMeasurementsMainWidget(ui.centralwidget, ui.listWidget, ui.toolBar);
// 		QObject::connect(bodyMeasurementsMainWidget,SIGNAL(updateToolBar()),this,SLOT(setToolBar()));
// 		/*QObject::connect(bodyMeasurementsMainWidget, SIGNAL(setToolBar(int)), this, SLOT(setToolBar(int)));
// 		*/ui.hboxLayout->addWidget(bodyMeasurementsMainWidget);	
// 		bodyMeasurementsMainWidget->hide();

		qtrainerWelcomsWidget = new QtrainerWelcomsWidget(ui.centralwidget);
		ui.hboxLayout->addWidget(qtrainerWelcomsWidget);	
		qtrainerWelcomsWidget->show();
		QObject::connect(qtrainerWelcomsWidget,SIGNAL(signalfinished(QString)),this, SLOT(openproject(QString)));
		QObject::connect(qtrainerWelcomsWidget,SIGNAL(newProfile()),this, SLOT(newproject()));
		

		///profiles settings widget
// 		settingswidget = new Settings(ui.stackedWidget, filehandlerPowerTraining);
// 		settingswidget->setMinimumSize(QSize(300, 300));
// 		ui.stackedWidget->insertWidget(1,settingswidget);
		
/**
		///Planner
		plannerwidget = new PlannerWrap(ui.stackedWidget,filehandlerPowerTraining);
		///plannerwidget->hide();
///		ui.stackedWidget->insertWidget(1,plannerwidget);
		plannerwidget->setMinimumSize(QSize(300, 300));

		///add data widget (scrollable)
//  		scrollareaadd = new QScrollArea(ui.stackedWidget);	
//  		ui.stackedWidget->insertWidget(2,scrollareaadd);
// 		adddatawidget = new AddData(scrollareaadd, filehandlerPowerTraining);
//  		adddatawidget->setMinimumSize(300,300);
//  		scrollareaadd->setWidget(adddatawidget);
		adddatawidget = new AddData(ui.stackedWidget, filehandlerPowerTraining);
/// 		ui.stackedWidget->insertWidget(2,adddatawidget); ///moved to after we know what profiletype we are loading
		adddatawidget->setMinimumSize(QSize(300, 300));
		///adddatawidget->hide();
		addbodydatawidget = new AddBodyData(ui.stackedWidget);
		///addbodydatawidget->hide();
		addbodydatawidget->setMinimumSize(QSize(300, 300));
		

		///plotwidget (scrollable)
		scrollareaplot = new QScrollArea(ui.stackedWidget);
		scrollareaplot->setFrameShape(QFrame::NoFrame);
		scrollareaplot->setFrameShadow(QFrame::Plain);
		///scrollareaplot->hide();
//		ui.stackedWidget->insertWidget(3,scrollareaplot);
		plotwidget = new PlotWidget(scrollareaplot, filehandlerPowerTraining);
		plotwidget->setMinimumSize(QSize(300, 300));
		scrollareaplot->setWidget(plotwidget);
	
		///tablewidget (auto scrollable)
		grid= new Grid(ui.stackedWidget, filehandlerPowerTraining);
		grid->setMinimumSize(QSize(300, 300));
		///grid->hide();
//		
///		ui.stackedWidget->insertWidget(4,grid);
	
		///programs displayer (srollable)
		scrollareaprograms = new QScrollArea(ui.stackedWidget);
		scrollareaprograms->setFrameShape(QFrame::NoFrame);
		scrollareaprograms->setFrameShadow(QFrame::Plain);
		///scrollareaprograms->hide();
///		ui.stackedWidget->insertWidget(5,scrollareaprograms);
		programswidget = new ViewAndManageSchedule(scrollareaprograms, filehandlerPowerTraining);
		QObject::connect(programswidget,SIGNAL(reloadScheduleNames()),grid, SLOT(reloadOtherScheduleOccurrences()));	
		programswidget->setMinimumSize(QSize(300, 300));
		scrollareaprograms->setWidget(programswidget);
		//ui.stackedWidget->insertWidget(5,programswidget);

		///add or remove or rename exercises widget (srollable)
 		exerciseswidget = new ViewAndManageExercise(ui.stackedWidget, filehandlerPowerTraining);
// 		exerciseswidget->setMinimumSize(QSize(300, 300));
		///exerciseswidget->hide();
/// 		ui.stackedWidget->insertWidget(6,exerciseswidget);
		

		ui.stackedWidget->setCurrentIndex(0);	///welcomeslabel as standard
		
		ui.groupBox_2->hide(); ///this is the information dialog
		ui.actionsGroupBox->hide(); ///actions group box

		setconnections();
		QString text = tr("<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Talk about Sports or Qtrainer on the Qtrainer-Forum: <span style=\" text-decoration: underline; color:#0000ff;\"><a href=\"");
		QSettings settings("ToonSoft", "Qtrainer");
		settings.beginGroup("ProgramSettings");
		text.append(settings.value("ForumURL").toString());
		text.append("\">");
		text.append(settings.value("ForumURL").toString());
		text.append("</a></span></p></body></html>");
		ui.labelForum->setText(text);
		settings.endGroup();
*/
		
	
	}

	
	void MainWindow::setconnections()
	{
/**	QObject::connect(plannerwidget,SIGNAL(updateTrainingInformation()),this, SLOT(updateTrainingInformation()));
	QObject::connect(plannerwidget,SIGNAL(updateTrainingInformation()),adddatawidget, SLOT(trainingsChanged()));

	///when exercises are added/renamed/removed
	QObject::connect(exerciseswidget,SIGNAL(redrawNeeded()),adddatawidget,SLOT(reloadWidgets()));
	QObject::connect(exerciseswidget,SIGNAL(redrawNeeded()),plotwidget,SLOT(reloadWidgets()));
	QObject::connect(exerciseswidget,SIGNAL(redrawNeeded()),grid,SLOT(redraw()));
	///when datapoints are added
	QObject::connect(adddatawidget,SIGNAL(dataPointAdded(int)),plotwidget,SLOT(redraw(int)));
	QObject::connect(adddatawidget,SIGNAL(dataPointAdded(int)),grid,SLOT(redraw(int)));
	QObject::connect(adddatawidget,SIGNAL(dataPointAdded(int)),this,SLOT(updateInformation(int)));
		///resize events, width of scrollarea widgets must be adjusted.
*/
// 	QObject::connect(this,SIGNAL(resizeWidgets()),powerTrainingMainWidget,SLOT(rescale()));
// 	QObject::connect(this,SIGNAL(resizeWidgets()),bodyMeasurementsMainWidget,SLOT(rescale()));
	}

	
	
	void MainWindow::resizeEvent(QResizeEvent *event)
	{
	emit resizeWidgets();
	}



	/**
	 * This method updates the InformationItem's Widget. It displays the progress ...
	 */
/**	void MainWindow::updateInformation(int ExeciseThatRecievedANewDataPoint)
	{
	///not yet fully implemented
//	ui.labelTip->hide();
//	ui.labelScheduleTip->hide();
//	ui.labelHartBeat->hide();
	
		///progress
		///settings	
		QSettings settings("ToonSoft", "Qtrainer");
		settings.beginGroup("ProgramSettings");
		if(settings.value("ShowProgress").toString()=="true")
		{
		ui.progressLabel->setText(tr("Qtrainer is still calculating your progress..."));
		ui.progressLabel->show();
		QString numberstring = settings.value("NumberOfProgressPoints").toString();
		settings.endGroup();
 		int numberint= numberstring.toInt();
		CalculateProgress *myProgress = new CalculateProgress(this,filehandlerPowerTraining,numberint, mutex_for_thread);
		myProgress->start();
		QObject::connect(myProgress, SIGNAL(finished(QString, QString)), this, SLOT(setProgress(QString, QString)));
		QObject::connect(myProgress, SIGNAL(takingtoolong()), this, SLOT(askUserToTurnOfProgress()));
		}
	
		else {ui.progressLabel->hide();}
		
		updateTrainingInformation();	
	}
*/
	/**
	*SLOT updates the label that informs about the next trainings
	*/
/**	void MainWindow::updateTrainingInformation(){

	///next training
	QString nextTraining=tr("Your next training is: ");
	QList<Training*> list = QList<Training*>(filehandlerPowerTraining->getTrainings()); ///copy of returned value
	Training *result = new Training(QMap<QString,QStringList>(),QList<QString>(), QDate::currentDate().addYears(999));
	QListIterator<Training*> i(list);

 	while (i.hasNext()){
		Training *myTraining = i.next();
		if(myTraining->getDate()>=QDate::currentDate() && myTraining->getDate()<result->getDate()){
		result = myTraining;
		}
	}
	if(result->getDate() == QDate::currentDate().addYears(999)) {
		nextTraining.append(tr("No trainings are planned in the future")); 
		ui.showTrainingButton->hide();
		ui.actionsGroupBox->hide();
		}
	else if(result->getDate() == QDate::currentDate()){nextTraining.append(tr("today")); 
		ui.showTrainingButton->setText(tr("Show today's training"));
		ui.showTrainingButton->show();
		ui.actionsGroupBox->show();
		}
	else if(result->getDate().addDays(-1) == QDate::currentDate())
		{nextTraining.append(tr("tomorrow"));
		ui.showTrainingButton->setText(tr("Show tomorrow's training"));
		ui.showTrainingButton->show();
		ui.actionsGroupBox->show();
		}
	else if(result->getDate() < QDate::currentDate()) {
		nextTraining = QString(tr("No trainings are planned in the future"));
		ui.showTrainingButton->hide();
		ui.actionsGroupBox->hide();
		}
	else {nextTraining.append(StringDate(result->getDate()).getQString());
		ui.showTrainingButton->setText(tr("Show training of ")+StringDate(result->getDate()).getQString());
		ui.showTrainingButton->show();
		ui.actionsGroupBox->show();
		}
	ui.nextTrainingLabel->setText(nextTraining);

	}
*/

	/**
	*SLOT: sets the progress to progress
	*/
/**	void MainWindow::setProgress(QString progressstring, QString numberstring){
		ui.progressLabel->setText(tr("You have made ")+progressstring+tr("% progress over the last ")+numberstring+tr(" (or less) training-datapoints."));
		ui.progressLabel->show();

	}
*/

	/**
	*This method ask the user to turn off the feature: "show progress", call this function when calculating
	*the progress slows down Qtrainer
	*/
/**	void MainWindow::askUserToTurnOfProgress(){

	if(!isMessageBoxProgressAlreadyShown){
	QMessageBox msgBox;
	msgBox.setText(tr("Qtrainer has noticed that (re)calculating the progress\n you have made is slowing down Qtrainer. Do you want to deactivate this feature?"));
	msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
	msgBox.setIcon(QMessageBox::Warning);
	msgBox.setWindowTitle(tr("Calculating Process slows down QTrainer"));
	isMessageBoxProgressAlreadyShown=true;
 	switch(msgBox.exec()){
	case QMessageBox::Yes:
		QSettings settings("ToonSoft", "Qtrainer");
		settings.beginGroup("ProgramSettings");
		settings.setValue("ShowProgress","false");
		settings.endGroup();
	break;
	}
	isMessageBoxProgressAlreadyShown=false;
	}

	}
*/

	/**
	 *slot: when saving the configuration we need to take some actions
	 */
	void MainWindow::configurationChanged()
	{
		if(loggedin){
			if(powertraining){powerTrainingMainWidget->updateInformation(0);}
		}
	}

	void MainWindow::openAboutDialog()
	{
	QMessageBox msgBox;
		msgBox.about(0,"About Qtrainer", tr("Qtrainer is a 'personal home trainer'.\nDeveloped by Toon Muylkens.\nFor Informtation and remarks.:  http://tuxer.ulyssis.be/homepage/qtrainer.html\nFeel free to translate Qtrainer to your native language, let me know when you plan on doing that."));
	}

	void MainWindow::exportProfile()
	{
		QString pathandfilename = QFileDialog::getSaveFileName(this, tr("Export Profile To"),
                                                 QDir::homePath());
		if(pathandfilename.size()!=0){
		QSettings settings("ToonSoft", "Qtrainer");
		settings.beginGroup("ProgramSettings");
		QString profilePath=(settings.value("Profile_Path")).toString();
		settings.endGroup();
		profilePath.append("/");
		profilePath.append(filehandlerPowerTraining->getprofilename());
		profilePath.append(".QProfile");
		
		QFile file(profilePath);
		if(QFile::exists(pathandfilename)){QFile(pathandfilename).remove();} ///we remove the old file
		file.copy(pathandfilename); ///in case the old file still exists, it will NOT override
		}
	}

	void MainWindow::recoverProfile()
	{
	///TODO rewrite: make it more flexible and make it work :-)
	if(loggedin && powertraining){
	QMessageBox msgBox;
	msgBox.setText(tr("Qtrainer automaticly makes backups of your profile.\nIn case of dataloss you can try to recover your data by loading the backup.\nDo you want to load the backup?"));
	msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
	msgBox.setIcon(QMessageBox::Warning);
	msgBox.setWindowTitle(tr("Qtrainer Recover From Backup"));
 	switch(msgBox.exec()){
	case QMessageBox::Yes:
		///Make paths
		QString profilename = filehandlerPowerTraining->getprofilename();
		QSettings settings("ToonSoft", "Qtrainer");
		settings.beginGroup("ProgramSettings");
		QString profilePathDest=(settings.value("Profile_Path")).toString();
		settings.endGroup();
		profilePathDest.append("/");
		profilePathDest.append(profilename);
		profilePathDest.append(".QProfile");
		QString profilePathSource = QString(profilePathDest+"~");
		///logout
		logout();
		///copy		
		QFile file(profilePathSource);
		if(QFile::exists(profilePathDest)){QFile(profilePathDest).remove();} ///overriding
		file.copy(profilePathDest);
		///login
		filehandlerPowerTraining->setprofilename(profilename);
//		loadnewproject();
		break;
	
		}
	}
	else{
		QMessageBox msgBox;
		msgBox.setText(tr("Recovering from backup currently isn't working good in Qtrainer."));
		msgBox.setStandardButtons(QMessageBox::Ok );
		msgBox.setIcon(QMessageBox::Warning);
		msgBox.setWindowTitle(tr("Qtrainer Recover From Backup"));
	 	msgBox.exec();
		}
	}

	/**
	*hides the icons in the left frame, not necessarry for the current profile, and shows the others
	*/
// 	void MainWindow::setLeftFrame(){
// 		InformationItem->setHidden(!powertraining);
// 		ViewPlannerItem->setHidden(!powertraining);
// 		AddDataItem->setHidden(!powertraining && !body);
// 		ViewDataPlottedItem->setHidden(!powertraining && !body);
// 		ViewDataTabledItem->setHidden(!powertraining);
// 		ViewProgramsItem->setHidden(!powertraining);
// 		ViewExercisesItem->setHidden(!powertraining);
// 	}





/**
*SLOT: the name of a trainingschedule may be changed => reload the tablewidget (second tab)
*/
// void MainWindow::someTrainingScheduleChanged(QString oldName, TrainingSchedule *newschedule){
// powerTrainingMainWidget->someTrainingScheduleChanged(oldName,newschedule);
// }
///nog nodig?


