//
// C++ Implementation: PowerTrainingPowerTrainingMainWidget
//
// Description: 
//
//
// Author: Muylkens Toon <toon.muylkens@student.kuleuven.be>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "PowerTrainingMainWidget.h"
//       #include <stdio.h>
//     #include <iostream>
//      using namespace std;


/**
*Constructs a new PowerTrainingMainWidget
*@param filehandler: A legal filehandler with a legal profile loaded into it
*@param parent: parent widget
*@param leftList: QListWidget used for browsing this BodyMeasurementsMainWidget
*@param toolBar: QToolBar used to place icons for common actions used by this BodyMeasurementsMainWidget
*/
PowerTrainingMainWidget::PowerTrainingMainWidget(ConfigFileHandlerPowerTraining *filehandler, QWidget *parent, QListWidget *leftList, QToolBar *toolBar)
     : QWidget(parent)
{
 	ui.setupUi(this);
	this->leftList = leftList;
	this->toolBar = toolBar;
	this->filehandlerPowerTraining = filehandler;

	///some more gui stuff:
	//QHBoxLayout *myLayout = new QHBoxLayout(ui.page);
	//groupBox_2 = new QGroupBox(ui.page);	///the information group box
    	//QGridLayout *gridLayout = new QGridLayout(groupBox_2);
    	//gridLayout->setHorizontalSpacing(6);
    	//gridLayout->setVerticalSpacing(6);
    	//gridLayout->setContentsMargins(9, 9, 9, 9);
	informationWidget = new InformationWidget(ui.page);

	ui.vboxLayout1->addWidget(informationWidget);


//     	progressLabel = new QLabel(groupBox_2);
//     	gridLayout->addWidget(progressLabel, 0, 0, 1, 1);
// 	labelForum = new QLabel(groupBox_2);
//     	labelForum->setWordWrap(true);
//     	labelForum->setTextInteractionFlags(Qt::TextBrowserInteraction);
// 	gridLayout->addWidget(labelForum, 2, 0, 1, 1);
// 	nextTrainingLabel = new QLabel(groupBox_2);
//     	gridLayout->addWidget(nextTrainingLabel, 1, 0, 1, 1);
// 	profileLabel = new QLabel(groupBox_2);
//     	gridLayout->addWidget(profileLabel, 3, 0, 1, 1);
// 	ui.vboxLayout1->addWidget(groupBox_2);
//     	actionsGroupBox = new QGroupBox(ui.page);	///the actions groupbox
//     	QGridLayout *gridLayout1 = new QGridLayout(actionsGroupBox);
//     	showTrainingButton = new QPushButton(actionsGroupBox);
// 	addTestDataButton = new QPushButton(tr("Enter test data"),actionsGroupBox);
// 	addLatestScheduleButton = new QPushButton(tr("Enter data from the latest schedule"),actionsGroupBox);
//     	gridLayout1->addWidget(showTrainingButton, 0, 0, 1, 1);
//     	gridLayout1->addWidget(addTestDataButton, 1, 0, 1, 1);
// 	gridLayout1->addWidget(addLatestScheduleButton, 2, 0, 1, 1);
// 	
// 	QSpacerItem *spacerItem1 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
// 	gridLayout1->addItem(spacerItem1, 0, 1, 1, 1);
// 	ui.vboxLayout1->addWidget(actionsGroupBox);
// 	QSpacerItem *spacerItem2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
// 	ui.vboxLayout1->addItem(spacerItem2);
// 
// 	groupBox_2->setTitle(QApplication::translate("MainWidget", "Information", 0, QApplication::UnicodeUTF8));
// 	progressLabel->setText(QApplication::translate("MainWidget", "Your progress is: ", 0, QApplication::UnicodeUTF8));
// 	labelForum->setText(QApplication::translate("MainWidget", "Talk about Sports or Qtrainer on the Qtrainer-Forum:", 0, QApplication::UnicodeUTF8));
// 	nextTrainingLabel->setText(QApplication::translate("MainWidget", "Your next training is: ", 0, QApplication::UnicodeUTF8));
// 	profileLabel->setText(QApplication::translate("MainWidget", "Profilename:", 0, QApplication::UnicodeUTF8));
// 	actionsGroupBox->setTitle(QApplication::translate("MainWidget", "Actions", 0, QApplication::UnicodeUTF8));
// 	showTrainingButton->setToolTip(QApplication::translate("MainWidget", "Show or Print the the first Training to come", 0, QApplication::UnicodeUTF8));
// 	showTrainingButton->setText(QApplication::translate("MainWidget", "Show Latest Training", 0, QApplication::UnicodeUTF8));

	///end of gui stuff
	makeActions();	

	isMessageBoxProgressAlreadyShown=false;
	mutex_for_thread = new QMutex();
	active=false;

	
}

/**
*this method constructs all the actions needed by this PowerTrainingMainWidget
*/
void PowerTrainingMainWidget::makeActions(){
   
    actionPlan_Training = new QAction(this);
    actionPlan_Training->setObjectName(QString::fromUtf8("actionPlan_Training"));
    actionPlan_Training->setIcon(QIcon(QString::fromUtf8(":/planner/filenew.png")));
    actionRemove_Training = new QAction(this);
    actionRemove_Training->setObjectName(QString::fromUtf8("actionRemove_Training"));
    actionRemove_Training->setIcon(QIcon());
    actionUpload = new QAction(this);
    actionUpload->setObjectName(QString::fromUtf8("actionUpload"));
    actionUpload->setIcon(QIcon(QString::fromUtf8(":/planner/upload.png")));
    actionAdd_Exercise = new QAction(this);
    actionAdd_Exercise->setObjectName(QString::fromUtf8("actionAdd_Exercise"));
    actionAdd_Exercise->setIcon(QIcon(QString::fromUtf8(":/planner/add.png")));
    actionAdd_Schedule = new QAction(this);
    actionAdd_Schedule->setObjectName(QString::fromUtf8("actionAdd_Schedule"));
    actionAdd_Schedule->setIcon(QIcon(QString::fromUtf8(":/planner/add.png")));
    actionSave_All = new QAction(this);
    actionSave_All->setObjectName(QString::fromUtf8("actionSave_All"));
    actionSave_All->setIcon(QIcon(QString::fromUtf8(":/planner/fileexport.png")));

    actionPlan_Training->setText(QApplication::translate("MainWindow", "Plan Training", 0, QApplication::UnicodeUTF8));
    actionRemove_Training->setText(QApplication::translate("MainWindow", "Remove Training", 0, QApplication::UnicodeUTF8));
    actionUpload->setText(QApplication::translate("MainWindow", "Upload", 0, QApplication::UnicodeUTF8));
    actionAdd_Exercise->setText(QApplication::translate("MainWindow", "Add Exercise", 0, QApplication::UnicodeUTF8));
    actionAdd_Schedule->setText(QApplication::translate("MainWindow", "Add Schedule", 0, QApplication::UnicodeUTF8));
    actionSave_All->setText(QApplication::translate("MainWindow", "Save All", 0, QApplication::UnicodeUTF8));

}

/**
*This method makes all the QListWidgetItems that are needed when this widget is active
*/
void PowerTrainingMainWidget::makeQListWidgetItems(){
	leftList->clear();
	const QSize size = QSize(32,32);
	leftList->setIconSize(size);
	leftList->setSpacing(5);
	InformationItem = new QListWidgetItem(tr("Information"),leftList);
	InformationItem->setIcon(QIcon(":/left/information.png"));
	///SettingsItem = new QListWidgetItem(tr("Profile Settings"),leftList);
	ViewPlannerItem= new QListWidgetItem(tr("Trainings"),leftList);
	ViewPlannerItem->setIcon(QIcon(":/left/trainings.png"));
	AddDataItem = new QListWidgetItem(tr("Add Data-Points"),leftList);
	AddDataItem->setIcon(QIcon(":/left/datapoints.png"));
	ViewDataPlottedItem = new QListWidgetItem(tr("Plots"),leftList);
	ViewDataPlottedItem->setIcon(QIcon(":/left/plots.png"));
	ViewDataTabledItem = new QListWidgetItem(tr("Grid"),leftList);
	ViewDataTabledItem->setIcon(QIcon(":/left/grid.png"));
	ViewProgramsItem = new QListWidgetItem(tr("Schedules"),leftList);
	ViewProgramsItem->setIcon(QIcon(":/left/schedules.png"));
	ViewExercisesItem= new QListWidgetItem(tr("Exercises"),leftList);
	ViewExercisesItem->setIcon(QIcon(":/left/exercises.png"));
}

/**
*This method return pointers of all the InformationItems needed when this widget is active
*They are oreded by index! 0->list.size()-1
*/
QList<QListWidgetItem*> PowerTrainingMainWidget::getQListWidgetItem(){
	QList<QListWidgetItem*> list;
	list.append(InformationItem);
	list.append(AddDataItem);
	list.append(ViewDataPlottedItem);
	list.append(ViewDataTabledItem);
	list.append(ViewProgramsItem);
	list.append(ViewExercisesItem);
	list.append(ViewPlannerItem);
	return list;
}


/**
*Slot: an item on the leftList has been clicked
*/
void PowerTrainingMainWidget::itemhasbeenchanged(QListWidgetItem *current)
{
if(active){
	if(InformationItem->isSelected()){
		setCurrentIndex(0);
		setToolBar(0);
		}

	if(ViewPlannerItem->isSelected()){
		setCurrentIndex(1);
		setToolBar(1);
		}
	if(AddDataItem->isSelected()){
		setCurrentIndex(2);
		setToolBar(2);
		}
	if(ViewDataPlottedItem->isSelected()){
		setCurrentIndex(3);
		setToolBar(3);
		}		
	if(ViewDataTabledItem->isSelected()){
		setCurrentIndex(4);
		setToolBar(4);
		}
	if(ViewProgramsItem->isSelected()){
		setCurrentIndex(5);
		setToolBar(5);
		}
	if(ViewExercisesItem->isSelected()){
		setCurrentIndex(6);
		setToolBar(6);
		}

}
}

/**
*Activates widget that allows the user to enter the data from the test schedule
*/
void PowerTrainingMainWidget::addTestDataButtonPressed(){
setCurrentIndex(2);
adddatawidget->selectTab(0);
//TODO Make this work => the right collumn in the left frame is selected emit setCurrentIndexInLeftFrame(2);
}

/**
*Activates widget that allows the user to enter the data from the test schedule
*/
void PowerTrainingMainWidget::showTestScheduleButtonPressed(){
	programswidget->showSchedule(getExercisesInNeedForTestData(),QString("Test"));
}



/**
*Activates widget that allows the user to enter the data from a schedule!=testschedule
*/
void PowerTrainingMainWidget::addLatestScheduleButtonPressed(){
setCurrentIndex(2);
adddatawidget->insertDataForTraining(mostRecentTrainingInThePast);
//TODO Make this work => the right collumn in the left frame is selected emit setCurrentIndexInLeftFrame(2);
}

/**
*Depending on which module is selected, other icons must be shown.
*stackIndex corresponds to the selected widget in the stackWidget
*/
void PowerTrainingMainWidget::setToolBar(int stackIndex){
emit updateToolBar();

	if(stackIndex==0||stackIndex==2||stackIndex==4){
	/*toolBar->addAction(actionNew_Project);
    	toolBar->addAction(actionOpen_Existing_Project);
	toolBar->addAction(actionLogout);
    	toolBar->addAction(actionExit_Qtrainer);
	*/}
	else if(stackIndex==3){
	///plots
	toolBar->addSeparator();
	toolBar->addAction(actionUpload);
	/*toolBar->addSeparator();
	toolBar->addAction(actionNew_Project);
    	toolBar->addAction(actionOpen_Existing_Project);
	toolBar->addAction(actionLogout);
    	toolBar->addAction(actionExit_Qtrainer);
	*/}
	else if(stackIndex==5){
	///schedules
	toolBar->addSeparator();
	toolBar->addAction(actionAdd_Schedule);

	/*toolBar->addSeparator();
	toolBar->addAction(actionNew_Project);
    	toolBar->addAction(actionOpen_Existing_Project);
	toolBar->addAction(actionLogout);
    	toolBar->addAction(actionExit_Qtrainer);
	*/}
	else if(stackIndex==6){
	///exercises
	toolBar->addSeparator();
	toolBar->addAction(actionSave_All);
	toolBar->addAction(actionAdd_Exercise);
	/*toolBar->addSeparator();
    	toolBar->addAction(actionNew_Project);
    	toolBar->addAction(actionOpen_Existing_Project);
	toolBar->addAction(actionLogout);
    	toolBar->addAction(actionExit_Qtrainer);	
    	*/}
	if(stackIndex==1){
	///planner
	toolBar->addSeparator();
    	toolBar->addAction(actionPlan_Training);
    	///toolBar->addAction(actionUpload);
	/*toolBar->addSeparator();
	toolBar->addAction(actionNew_Project);
    	toolBar->addAction(actionOpen_Existing_Project);
	toolBar->addAction(actionLogout);
    	toolBar->addAction(actionExit_Qtrainer);	*/
	}

	
	}



/**
*The index of the stacked widget is set to 'index'
*/
void PowerTrainingMainWidget::setCurrentIndex(int index){
ui.stackedWidget->setCurrentIndex(index);
if(index==2){
	adddatawidget->rescale(); ///still needs to be executed because Qt seems to only automaticly resize the widget when it is NOT hidden.
	}
if(index==3){
	plotWidget->rescale(); ///still needs to be executed because Qt seems to only automaticly resize the widget when it is NOT hidden.
	}
if(index==5){
	programswidget->rescale(); ///still needs to be executed because Qt seems to only automaticly resize the widget when it is NOT hidden.
	}
if(index==6){
	exerciseswidget->rescale();///still needs to be executed because Qt seems to only automaticly resize the widget when it is NOT hidden.
	}
}

/**
*Prepare for log-out gui status
*/
void PowerTrainingMainWidget::logout(){
setCurrentIndex(0);
// groupBox_2->hide();
//actionsGroupBox->hide();
active=false;
leftList->clear();
}

/**
*Prepare for log-in gui status and update subWidgets
*/
void PowerTrainingMainWidget::login(){
makeQListWidgetItems();
// groupBox_2->show();
//actionsGroupBox->show();
setCurrentIndex(0);
///Start with the welcomsitem
QString text=tr("Profile name: ");
text.append(filehandlerPowerTraining->getprofilename());
text.append(" (");
text.append(filehandlerPowerTraining->getSport());
text.append(")");
informationWidget->setProfileLabel(text);

adddatawidget->loadsettings(filehandlerPowerTraining);
fillPlotWidget();
	

exerciseswidget->loadsettings(filehandlerPowerTraining);
grid->loadsettings(filehandlerPowerTraining);
programswidget->loadsettings(filehandlerPowerTraining);
plannerwidget->loadsettings(filehandlerPowerTraining);
	
updateInformation(0);
active=true;
}

/**
*Clears the QtrainerPlotWidget and refills it using the filehandlerPowerTraining
*/
void PowerTrainingMainWidget::fillPlotWidget(){
plotWidget->clear();
	int size = filehandlerPowerTraining->getExercise()->getNbOfExercises();
	for(int i=0;i<size;i++){
		///loop over all exercises
		int index = filehandlerPowerTraining->getExercise()->getIndexes().at(i);
		QString name = filehandlerPowerTraining->getExercise()->getName(index);
		Exercise *ex = filehandlerPowerTraining->getExercise()->getExercise(index);
		//ex = filehandlerPowerTraining->getExercise()->getExercise(name);
		int nb = ex->getNbOfPointsToPlot();
		//QVector<QPointF> vector = filehandlerPowerTraining->getvector(name);
		QVector<QPointF> vector = ex->getVector();
		plotWidget->addDataSet(vector,nb,name , ex->getBezier(), ex->getLine(), ex->getSpline());
		}

}

/**
*Execute this method when openingen a new PowerTraining profile.
*It loads all the neccesary widgets into the stack
*/
void PowerTrainingMainWidget::loadsettings(ConfigFileHandlerPowerTraining *filehandlerPowerTraining){

	this->filehandlerPowerTraining = filehandlerPowerTraining;

	///Planner
	plannerwidget = new PlannerWrap(ui.stackedWidget,filehandlerPowerTraining);
	ui.stackedWidget->insertWidget(1,plannerwidget);
	plannerwidget->setMinimumSize(QSize(300, 300));

	///add data widget (scrollable by itself)
	adddatawidget = new AddData(ui.stackedWidget, filehandlerPowerTraining);
	ui.stackedWidget->insertWidget(2,adddatawidget);

	adddatawidget->setMinimumSize(QSize(300, 300));
	
	///plotwidget (scrollable)
	scrollareaplot = new QScrollArea(ui.stackedWidget);
	scrollareaplot->setFrameShape(QFrame::NoFrame);
	scrollareaplot->setFrameShadow(QFrame::Plain);
	ui.stackedWidget->insertWidget(3,scrollareaplot);

///NEW PLOT FRAMEWORK	
  	plotWidget = new QtrainerPlotWidget(ui.stackedWidget);
  	plotWidget->setText(tr("Here the datapoints from the test-schedule are plotted.\n"
"       *On the Y-axis you see the values you entered\n"
"       *On the X-axis you see the number of days from today.\n"
"You can choose how many datapoints to use for the plot. Maybe you don't want to plot really old data.  If less than two datapoints are available, no plot is available."));
 	scrollareaplot->setWidget(plotWidget);
	plotWidget->show();
///filling see login  	
	
	

//  	QList<Measurable*> list = filehandlerBodyMeasurements->getMeasurables();
//  	int size1 = list.size();
//  	for (int i=0;i<size1; i++){
//  		QVector<QPointF> vector;
//  		if(list.at(i)->isBodyPart()){
//  			vector = ((BodyPart*)list.at(i))->getVector();
//  			}
//  		if(list.at(i)->isBmi()){
//  			vector = ((Bmi*)list.at(i))->getVector();
//  			filehandlerBodyMeasurements->getBmi()->setIndex(i);
//  			}		
//  		int number = list.at(i)->getNbOfPointsToPlot();
//  		bool bezier = list.at(i)->getBezier();
//  		bool line = list.at(i)->getLine();
//  		bool spline = list.at(i)->getSpline();
//  		QString name = list.at(i)->getName();
//  		plotBodyPartData->addDataSet(vector,number,name , bezier, line, spline);
//  	}
///END NEW PLOT FRAMEWORK	

 	///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));
	ui.stackedWidget->insertWidget(4,grid);
	
	///programs displayer (srollable)
	scrollareaprograms = new QScrollArea(ui.stackedWidget);
	scrollareaprograms->setFrameShape(QFrame::NoFrame);
	scrollareaprograms->setFrameShadow(QFrame::Plain);
	ui.stackedWidget->insertWidget(5,scrollareaprograms);
	programswidget = new ViewAndManageSchedule(scrollareaprograms, filehandlerPowerTraining);	
	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));
	ui.stackedWidget->insertWidget(6,exerciseswidget);
		
	ui.stackedWidget->setCurrentIndex(0);	///welcomeslabel as standard
		
//	groupBox_2->hide(); ///this is the information dialog
//	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>");
	informationWidget->setLabelForum(text);
	settings.endGroup();
}

/**
*Sets all the neccesary connections
*/
void PowerTrainingMainWidget::setconnections()
{

	QObject::connect(actionUpload, SIGNAL(triggered()),this , SLOT(uploadButtonPressed()));
	QObject::connect(actionSave_All, SIGNAL(triggered()), this, SLOT(saveAllExercises()));
	QObject::connect(actionAdd_Exercise, SIGNAL(triggered()), this, SLOT(addExercise()));
	QObject::connect(actionPlan_Training, SIGNAL(triggered()), this, SLOT(planTraining()));
	QObject::connect(actionAdd_Schedule,SIGNAL(triggered()),this, SLOT(addTrainingSchedule()));	

	

	QObject::connect(programswidget,SIGNAL(reloadScheduleNames()),grid, SLOT(reloadOtherScheduleOccurrences()));
	QObject::connect(plannerwidget,SIGNAL(updateTrainingInformation()),this, SLOT(updateTrainingInformation()));
	QObject::connect(plannerwidget,SIGNAL(updateTrainingInformation()),adddatawidget, SLOT(trainingsChanged()));

	QObject::connect(grid,SIGNAL(updateVisualisation()),this,SLOT(updateVisualisation()));

	///when exercises are added/renamed/removed
	QObject::connect(exerciseswidget,SIGNAL(redrawNeeded()),adddatawidget,SLOT(reloadWidgets()));
	///TODO reanable effect of the follewing line using the new plotframework:
	//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)),this,SLOT(updateVisualisation(int)));
	QObject::connect(exerciseswidget,SIGNAL(redrawNeeded()),this,SLOT(updateVisualisation()));
	//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(informationWidget->getShowTrainingButton(),SIGNAL(pressed()),this,SLOT(showLatestTraining()));
	QObject::connect(informationWidget->getAddTestDataButton(),SIGNAL(pressed()),this,SLOT(addTestDataButtonPressed()));
	QObject::connect(informationWidget->getAddLatestScheduleButton(),SIGNAL(pressed()),this,SLOT(addLatestScheduleButtonPressed()));
	QObject::connect(informationWidget->getShowTestScheduleButton(),SIGNAL(pressed()),this,SLOT(showTestScheduleButtonPressed()));

	///plotter
	QObject::connect(plotWidget,SIGNAL(savePlotMethodInProfile(QStringList,int)),this,SLOT(storePlotMethod(QStringList, int)));	
	QObject::connect(plotWidget,SIGNAL(saveNbOfPointsToPlotInProfile(int,int)),this,SLOT(storeNbPointsToPlot(int,int)));

}

/**
*SLOT: save the plotmethods into the profile
*/
void PowerTrainingMainWidget::storePlotMethod(QStringList list, int index){
filehandlerPowerTraining->getExercise()->setPlotMethod(list,index);
filehandlerPowerTraining->savedata();

}

/**
*SLOT: save the nb of points to use for plotting into the profile
*/
void PowerTrainingMainWidget::storeNbPointsToPlot(int number,int index){
filehandlerPowerTraining->savenumberofpointstoplot(filehandlerPowerTraining->getExercise()->getName(index),number);
}


/**
*Update all the visual representations of the bodyparts
*This means updating the plots, information dialogs, ...
*/
void PowerTrainingMainWidget::updateVisualisation(){
QList<Exercise*> exerciseList = filehandlerPowerTraining->getExercise()->getExercises();
int size1=exerciseList.size();
if(plotWidget->getNbOfPlotFrames() > size1){
	///an exercise was deleted
	fillPlotWidget();
}
else{
	///an exercise was modified or added
	for (int i=0;i<size1; i++){
		Exercise *ex = exerciseList.at(i);
		QString name = ex->getName();
		int nb = ex->getNbOfPointsToPlot();
		QVector<QPointF> vector = filehandlerPowerTraining->getvector(name);
		plotWidget->updateDataSet(vector, nb, name, i);
	}
}
updateInformation(0); ///TODO: fix updateInformation function. make it use the paramter or remove it
grid->redraw();
}


/**
*Update all the visual representations of the bodypart with index 'index'.
*This means updating the plots, information dialogs, ...
*/
void PowerTrainingMainWidget::updateVisualisation(int index){
	QString name = filehandlerPowerTraining->getExercise()->getName(index);
	int nb = filehandlerPowerTraining->getExercise()->getExercise(index)->getNbOfPointsToPlot();
	QVector<QPointF> vector = filehandlerPowerTraining->getvector(name);
	plotWidget->updateDataSet(vector, nb, name, index);

grid->redraw(index);

updateInformation(0); ///TODO: fix updateInformation function. make it use the paramter or remove it

}

/**
*reimplementation of resizeEvent to make subwidgets resize correctly
*/
void PowerTrainingMainWidget::resizeEvent(QResizeEvent * event) {
QWidget::resizeEvent(event);
rescale();
}


/**
*SLOT: Lets the sub-widgets adjust to the new size
*/
void PowerTrainingMainWidget::rescale(){
	exerciseswidget->rescale();
	programswidget->rescale();
	adddatawidget->rescale();
	plotWidget->rescale();
}

/**
* This method updates the InformationItem's Widget. It displays the progress ...
*/
void PowerTrainingMainWidget::updateInformation(int ExeciseThatRecievedANewDataPoint)
{
	///progress
	///settings	
	QSettings settings("ToonSoft", "Qtrainer");
	settings.beginGroup("ProgramSettings");
	if(settings.value("ShowProgress").toString()=="true")
	{
	informationWidget->setProgressLabel(tr("Qtrainer is calculating your progress..."));
	informationWidget->setVisibleProgressLabel(true);
	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 {informationWidget->setVisibleProgressLabel(false);}
	
	updateTrainingInformation();
	updateScheduleInformation();
	updateTipInformation();
}

/**
*Returns the names of all the exercises that havn't seen test data added for more then 30 days
*or don't have datapoints at all!
*/
QList<QString> PowerTrainingMainWidget::getExercisesInNeedForTestData(){
QList<Exercise*> exlist = filehandlerPowerTraining->getExercise()->getExercises();
	QList<QString> exlist_toLongAgo; //alle exercises waarvan het te lang geleden is dat je test deed
	for(int i=0;i<exlist.size();i++){
		if(exlist.at(i)->getNbOfDatapoints()>0){
			int index = exlist.at(i)->getMeasurements().size()-1;
			QDate mostrecent = exlist.at(i)->getMeasurements().at(index)->getDate().getQDate();
			if(mostrecent.daysTo(QDate::currentDate())>30){
				exlist_toLongAgo.append(exlist.at(i)->getName());
				}
			}
		else{
		exlist_toLongAgo.append(exlist.at(i)->getName());
			}
		}
return exlist_toLongAgo;
}

/**
*In the Actions section of the information tab a text informing the user of the importance of adding test-data
*is shown when it was more then one month ago he/she entered data.
*a button which displays the test schedule is shown.
*/
void PowerTrainingMainWidget::updateTipInformation(){
	
	QList<QString> exlist_toLongAgo = getExercisesInNeedForTestData();
	
	if(exlist_toLongAgo.size() ==0){
		informationWidget->setVisibleShowTestScheduleLabel(false);
		informationWidget->setVisibleShowTestScheduleButton(false);
		}
	else{
		informationWidget->setVisibleShowTestScheduleLabel(true);
		informationWidget->setVisibleShowTestScheduleButton(true);
		QString text= tr("You havn't entered test-data in more then 30 days for ");
		QString num;
		num.setNum(exlist_toLongAgo.size());
		text.append(num);
		text.append(tr(" exercises. Qtrainer needs the test-data to give you accurate schedules."));
		informationWidget->setShowTestScheduleLabel(text);
	}
}

/**
*SLOT updates the label that informs about the next trainings
*/
void PowerTrainingMainWidget::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")); 
		informationWidget->setVisibleShowTrainingButton(false);
//		actionsGroupBox->show();
		}
	else if(result->getDate() == QDate::currentDate()){nextTraining.append(tr("today")); 
		informationWidget->setShowTrainingButton((tr("Show today's training")));
		informationWidget->setVisibleShowTrainingButton(true);
//		actionsGroupBox->show();
		}
	else if(result->getDate().addDays(-1) == QDate::currentDate())
		{nextTraining.append(tr("tomorrow"));
		informationWidget->setShowTrainingButton((tr("Show tomorrow's training")));
		informationWidget->setVisibleShowTrainingButton(true);
//		actionsGroupBox->show();
		}
	else if(result->getDate() < QDate::currentDate()) {
		nextTraining = QString(tr("No trainings are planned"));
		informationWidget->setVisibleShowTrainingButton(false);
//		actionsGroupBox->show();
		}
	else {nextTraining.append(StringDate(result->getDate()).getQString());
		informationWidget->setShowTrainingButton(tr("Show training of ")+StringDate(result->getDate()).getQString());
		informationWidget->setVisibleShowTrainingButton(true);
//		actionsGroupBox->show();
		}
	informationWidget->setNextTrainingLabel(nextTraining);

	
//	QString nextTraining=tr("Enter training data: ");
	

}

/**
*Updates the status and text on the button in the actions group on the welcomes page
*When pressing the button after this methdod is executed the most recent schedule from the past
*Is opened for entering data into it.
*/
void PowerTrainingMainWidget::updateScheduleInformation(){
	///latest training
	QString string=tr("Enter data from training: ");
	QList<Training*> list = filehandlerPowerTraining->getTrainings(); 
	int max = list.size();
	Training *myTraining;
	if(max>0){
		myTraining = list.at(0);
		if(myTraining->getDate() > QDate::currentDate()){
			///Only trainings in the future present in Qtrainer
			informationWidget->setVisibleAddLatestScheduleButton(false);
			}
		else{
		int i=-1;
		while(i<max-1 && list.at(i+1)->getDate()<=QDate::currentDate()){
			i++;
			}
		myTraining = list.at(i);
		mostRecentTrainingInThePast= list.at(i);
		string.append(myTraining->getTitle());
		string.append(" - ");
		string.append(StringDate(myTraining->getDate()).getQString());
		informationWidget->setVisibleAddLatestScheduleButton(true);
		informationWidget->setAddLatestScheduleButton(string);
		}
	}
	else{
	///No trainings in Qtrainer
	informationWidget->setVisibleAddLatestScheduleButton(false);
	}
	///

}



/**
*SLOT: sets the progress to progress
*/
void PowerTrainingMainWidget::setProgress(QString progressstring, QString numberstring){
	informationWidget->setProgressLabel(tr("You have made ")+progressstring+tr("% progress over the last ")+numberstring+tr(" (or less) training-datapoints."));
	informationWidget->setVisibleProgressLabel(true);
}

/**
*This method ask the user to turn off the feature: "show progress", call this function when calculating
*the progress slows down Qtrainer
*/
void PowerTrainingMainWidget::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: show the most recent training when it exists.
*/
void PowerTrainingMainWidget::showLatestTraining(){
	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)){
	TrainScheduleDisplayer *displayer =  new TrainScheduleDisplayer(0);
	displayer->setWindowFlags(Qt::SubWindow);
	filehandlerPowerTraining->getTrainings();
	displayer->setTraining(result, filehandlerPowerTraining);
	displayer->show();
	}
}

/**
*SLOT: the name of a trainingschedule may be changed => reload the tablewidget (second tab)
*/
void PowerTrainingMainWidget::someTrainingScheduleChanged(QString oldName, TrainingSchedule *newschedule){
grid->loadsettings(filehandlerPowerTraining);
}


/**
*Triggered when upload button is pressed
* this method sends a signal to the active widget that the content in that widget must be uploaded.
*/
void PowerTrainingMainWidget::uploadButtonPressed(){
 	if(active){	
	plotWidget->upload();
	///TODO hier moet ie ook exercisen fzo uploaden
 	//emit uploadPlots();
 	}
 }

/**
*SLOT: saveallexercisesbutton is pressed
*/
void PowerTrainingMainWidget::saveAllExercises(){
exerciseswidget->saveAll();
}

/**
*SLOT: add an exercise by using the AddExercise dialog
*/
void PowerTrainingMainWidget::addExercise(){
AddExerciseDialog *dialog = new AddExerciseDialog(0,filehandlerPowerTraining);
dialog->loadsettings(filehandlerPowerTraining);
dialog->setWindowFlags(Qt::SubWindow);
dialog->show();
QObject::connect(dialog,SIGNAL(exerciseAdded()),this,SLOT(updateVisualisation()));
QObject::connect(dialog,SIGNAL(exerciseAdded()),adddatawidget,SLOT(reloadWidgets()));
QObject::connect(dialog,SIGNAL(exerciseTagListChanged()),exerciseswidget,SLOT(reloadAllTagLists()));
QObject::connect(dialog,SIGNAL(exerciseAdded()),exerciseswidget,SLOT(drawWidgets()));
}

/**
*SLOT: shows the plan training gui when triggered
*/
void PowerTrainingMainWidget::planTraining(){
plannerwidget->planTraining();
}

/**
*SLOT: a 'add new schedule' gui is opened
*/
void PowerTrainingMainWidget::addTrainingSchedule(){
programswidget->addSchedule();
}