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

AddOtherData::AddOtherData(QWidget *parent, ConfigFileHandlerPowerTraining *filehandler)
     : QWidget(parent)
{
     	ui.setupUi(this);
	this->filehandler = filehandler;
	training=false;
	schedule=false;
	busytabling=true;

	ui.trainingRadioButton->setChecked(true);
	//ui.scheduleRadioButton->setChecked(false);
	ui.finishButton->hide();
	ui.cancelButton->hide();
	ui.dateEdit->setDate(QDate::currentDate());

	selectExercises = new SelectExerciseWidget(ui.page3,filehandler);
	QVBoxLayout *layout1 = new QVBoxLayout(ui.page3);
	layout1->setMargin(0);
	layout1->addWidget(selectExercises);
//	selectExercises->show();

	setSignalsSlots();
}

/**
*load all profile depended data.
*/
void AddOtherData::loadsettings(ConfigFileHandlerPowerTraining *filehandler){
this->filehandler=filehandler;
fillComboBoxes();
///selectExercises->loadsettings();  we do this every time again, because in the mean time taggs can be added
}

/**
*Slot: the next button was pressed.
*/
void AddOtherData::nextPressed(){
if(ui.stackedWidget->currentIndex()==5 && training){
	if(nbOfSchedulesAlreadyEntered < nbOfSchedulesInTraining){
		QString scheduleName = pTraining->getTrainingSchedules().at(nbOfSchedulesAlreadyEntered);
		QStringList exerciseNames = pTraining->getTrainingSchedulesMap().value(scheduleName);
// 		QList<int> exercises = QList<int>();
// 		for(int i=0;i<exerciseNames.size();i++){
// 			for(int j=0;j<filehandler->getExercise()->getNbOfExercises();j++){
// 				if(exerciseNames.at(i)==filehandler->getExercise()->getName(j)){
// 					exercises.append(j);
// 					}
// 				}
// 			}
		loadEnterScheduleWidget(scheduleName,exerciseNames);
		ui.stackedWidget->setCurrentIndex(3);
		ui.nextButton->hide();
		ui.finishButton->show();
		}
	else{cancelPressed();}
	}


if(ui.stackedWidget->currentIndex()==4 && training){
	if(ui.trainingComboBox->currentIndex()!=-1){
		pTraining = trainingList.at(ui.trainingComboBox->currentIndex());
		nbOfSchedulesInTraining=pTraining->getTrainingSchedules().size();
		nbOfSchedulesAlreadyEntered = 0;
		QString num; num.setNum(nbOfSchedulesInTraining);
		ui.informationLabel->setText(tr("About to enter data of schedule 1 from ")+num);
		ui.stackedWidget->setCurrentIndex(5);
		ui.nextButton->show();
		ui.finishButton->hide();
		}
	else {cancelPressed();}
	}

if(ui.stackedWidget->currentIndex()==2 && schedule){
	loadEnterScheduleWidget(ui.schedulesComboBox->currentText(), selectExercises->getSelectedExercises() );
	ui.stackedWidget->setCurrentIndex(3);
	ui.nextButton->hide();
	ui.finishButton->show();
	}


if(ui.stackedWidget->currentIndex()==1 && schedule){
	///this->scheduleName = ui.schedulesComboBox->currentText();
	selectExercises->loadsettings(filehandler);
	ui.stackedWidget->setCurrentIndex(2);
	ui.finishButton->hide();
	ui.nextButton->show();
	}

if(ui.stackedWidget->currentIndex()==0){
	if(ui.trainingRadioButton->isChecked()){training=true;}
	if(ui.scheduleRadioButton->isChecked()){schedule=true;}

	if(schedule){
		ui.stackedWidget->setCurrentIndex(1);
		}
	
	if(training){
		ui.stackedWidget->setCurrentIndex(4);
		}
		ui.cancelButton->show();
		ui.nextButton->show();
		ui.finishButton->hide();
	
	}
}

/**
*Select the given Training for entering data
*/
void AddOtherData::insertDataForTraining(Training *myTraining){
training=true;
schedule=false;
pTraining = myTraining;
nbOfSchedulesInTraining=pTraining->getTrainingSchedules().size();
nbOfSchedulesAlreadyEntered = 0;
QString num; num.setNum(nbOfSchedulesInTraining);
ui.informationLabel->setText(tr("About to enter data of schedule 1 from ")+num);
ui.stackedWidget->setCurrentIndex(5);
ui.nextButton->show();
ui.finishButton->hide();
ui.cancelButton->show();
}

/**
*This function fills the table with all the sets and exercises of the selected schedule
*/
void AddOtherData::loadEnterScheduleWidget(QString schedulename, QList<QString> selectedExercises){
busytabling=true;
int i=ui.tableWidget->rowCount(); while(i !=0){i--; ui.tableWidget->removeRow(ui.tableWidget->rowCount()-1);}

bool schedulefound=false; //if we don't find a schedule with the given name...
TrainingSchedule *trainingSchedule = new TrainingSchedule();
QList<TrainingSchedule*> list = filehandler->getTrainingSchedules();
for(int i=0;i<list.size() && !schedulefound;i++){
///linear search. Find the schedule with the given name
if(list.at(i)->getName()==schedulename){
	trainingSchedule=list.at(i);
	schedulefound=true;
	}
}
if(schedulefound){
	ui.tableWidget->setColumnCount(5);
	ui.tableWidget->setColumnWidth(0,40);
	ui.tableWidget->setColumnWidth(1,200);
	QBrush brush = QBrush(Qt::lightGray, Qt::SolidPattern);
	QList<Exercise*> exerciseList = filehandler->getExercise()->getExercises();
	for(int rot=0;rot<trainingSchedule->getNumberOfRotations();rot++){
		int totIterations = trainingSchedule->getNumberOfTimesExerciseIsRepeatedInARotation(rot);
		for(int i=0; i<exerciseList.size();i++){
			Exercise *ex = exerciseList.at(i);
			if(selectedExercises.contains(ex->getName())){
				for(int iter=0;iter<totIterations;iter++){
				int row = ui.tableWidget->rowCount();
				ui.tableWidget->insertRow(row);
				ui.tableWidget->takeVerticalHeaderItem(row);
				QTableWidgetItem *itemSet = new QTableWidgetItem();
				QString set; set.setNum(rot+1);
				itemSet->setText(set);
				itemSet->setFlags(Qt::ItemIsEnabled);
				//itemSet->setBackground(brush);
				ui.tableWidget->setItem(row,0,itemSet);

				QTableWidgetItem *itemExercise = new QTableWidgetItem();
				itemExercise->setText(ex->getName());
				itemExercise->setFlags(Qt::ItemIsEnabled);
				//itemExercise->setBackground(brush);
				ui.tableWidget->setItem(row,1,itemExercise);

				QTableWidgetItem *itemPerformance = new QTableWidgetItem();
				QString performanceS;
				performanceS.setNum(trainingSchedule->getPerformance(rot,iter));
				itemPerformance->setText(performanceS);
				itemPerformance->setFlags(Qt::ItemIsEnabled);
				//itemPerformance->setBackground(brush);
				ui.tableWidget->setItem(row,4,itemPerformance);

				QTableWidgetItem *itemRepetitions = new QTableWidgetItem();
				QString repetitionsS;
				repetitionsS.setNum(trainingSchedule->getNumberOfTimesExerciseIsDone(rot,iter));
				itemRepetitions->setText(repetitionsS);
				itemRepetitions->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable |Qt::ItemIsEnabled);
				//itemRepetitions->setBackground(brush);
				ui.tableWidget->setItem(row,3,itemRepetitions);

				QTableWidgetItem *itemWeight = new QTableWidgetItem();
				int size = ex->getMeasurements().size();
				if(size>0){
					int index = size-1; ///most recent measurement
					PowerTrainingMeasurement *mes = ex->getMeasurements().at(index);
					int repetitions = trainingSchedule->getNumberOfTimesExerciseIsDone(rot,iter);
					int performance = trainingSchedule->getPerformance(rot,iter);
					float performancefloat=(100.0-performance)/100;
					float newrepetitions = repetitions+repetitions*performancefloat;
					float weightToUse = mes->normalize(mes->getWeight(),mes->getRepetitions(),newrepetitions);
					int weightToUseInt = (weightToUse);
					QString weight;
					weight.setNum(weightToUseInt);
					itemWeight->setText(weight);
					}


// 				int latestweight = filehandler->getlatestweight(i);
// 				int repetitions = trainingSchedule->getNumberOfTimesExerciseIsDone(rot,iter);
// 				int performance = trainingSchedule->getPerformance(rot,iter);
// 				float performancefloat=(100.0-performance)/100;
// 				float newrepetitions = repetitions+repetitions*performancefloat;
// 				if(latestweight!=0){
// 					float weightToUse = filehandler->normalize(latestweight,filehandler->getDefaultValueForRepetitions(),newrepetitions);
// 					int weightToUseInt = (weightToUse);
// 					QString weight;
// 					weight.setNum(weightToUseInt);
// 					itemWeight->setText(weight);
// 					}
				itemWeight->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable |Qt::ItemIsEnabled);
				ui.tableWidget->setItem(row,2,itemWeight);
				
				brush=swapBrush(brush);
				}
			}
		}
	}
	
	}
busytabling=false;
}

/**
 * swaps the colour between two colours, this is being used for example to have every
 * exercise display differently on a table
 * @return 
 */
QBrush AddOtherData::swapBrush(QBrush brush)
{
if(brush.color()==Qt::lightGray){brush.setColor(Qt::white);}
else {brush.setColor(Qt::lightGray);}
return brush;
}

/**
*Slot: the cancel button was pressed. Go back to first screen
*/
void AddOtherData::cancelPressed(){
training=false;
schedule=false;

ui.stackedWidget->setCurrentIndex(0);
ui.cancelButton->hide();
ui.finishButton->hide();
ui.nextButton->show();
}

/**
*SLOT: enters data into the QProfile and go back to welcomespage
*/
void AddOtherData::finishPressed(){
QList<int> weigths = QList<int>();
	QList<int> repetitions = QList<int>();
	for(int row=0;row<ui.tableWidget->rowCount();row++){
	weigths.append(ui.tableWidget->item(row,2)->text().toInt());
	repetitions.append(ui.tableWidget->item(row,3)->text().toInt());
	}


if(schedule){
	ScheduleOccurrence *scheduleOc = new ScheduleOccurrence(ui.schedulesComboBox->currentText(),ui.dateEdit->date(), selectExercises->getSelectedExercises(), weigths,repetitions);

	if(overridingExistingScheduleOc(scheduleOc)){
		QMessageBox msgBox;
		msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
		/*msgBox.setText(tr("You already entered a schedule occurrence on the given date and of the given type\nShould it be overwritten?"));*/
		msgBox.setText(tr("Another schedule on the given date has been found.\nDo you want to overwrite? \n(This will only remove the scheduling, not the scheme itself."));
		msgBox.setDetailedText(tr("You can edit existing schedule occurrences in the grid"));
 		switch (msgBox.exec()) 
			{
			case QMessageBox::Yes:
			filehandler->addScheduleOccurrence(scheduleOc);
			break;
			case QMessageBox::No:
     			//do nothing
			break;
 			}
		}
	cancelPressed();
	}

if(training &&  nbOfSchedulesAlreadyEntered<nbOfSchedulesInTraining){
	QString scheduleName = pTraining->getTrainingSchedules().at(nbOfSchedulesAlreadyEntered);
	ScheduleOccurrence *scheduleOc = new ScheduleOccurrence(scheduleName,pTraining->getDate(),pTraining->getTrainingSchedulesMap().value(scheduleName), weigths,repetitions);
	if(overridingExistingScheduleOc(scheduleOc)){
		QMessageBox msgBox;
		msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
		/*msgBox.setText(tr("You already entered a Schedule Occurrence on the given date and of the given type\nShould it be overwritten?"));*/
		msgBox.setText(tr("Another schedule on the given date has been found.\nDo you want to overwrite? \n(This will only remove the scheduling, not the scheme itself."));
		msgBox.setDetailedText(tr("You can edit existant Schedule Occurrences in the Grid"));
 		switch (msgBox.exec()) 
			{
			case QMessageBox::Yes:
			filehandler->addScheduleOccurrence(scheduleOc);
			nbOfSchedulesAlreadyEntered++;
			break;
			case QMessageBox::No:
     			nbOfSchedulesAlreadyEntered++;
			break;
 			}
		}
	else{
		filehandler->addScheduleOccurrence(scheduleOc);
		nbOfSchedulesAlreadyEntered++;
		}
		QString num2; num2.setNum(nbOfSchedulesInTraining);
		QString num1; num1.setNum(nbOfSchedulesAlreadyEntered+1);
		QString text = tr("About to enter data of schedule ");
		text.append(num1); text.append(tr(" from ")); text.append(num2);
		ui.informationLabel->setText(text);
		ui.stackedWidget->setCurrentIndex(5);
		ui.nextButton->show();
		ui.finishButton->hide();
	}

if(training && nbOfSchedulesAlreadyEntered==nbOfSchedulesInTraining){
	cancelPressed();
	}

}

/**
*Returns true if scheduleOc is going to override another schedulOc when saving
*/
bool AddOtherData::overridingExistingScheduleOc(ScheduleOccurrence *scheduleOc){
QString date = StringDate(scheduleOc->getDate()).getQString();
if(!filehandler->containsScheduleOccurrences(date)){
return false;
}
QList<ScheduleOccurrence> *list = filehandler->getScheduleOccurrences(date);
for(int i=0;i<list->size();i++){
	if(list->at(i).getName() == scheduleOc->getName()){return true;}
	}
return false;
}


/**
*Fill all the comboboxes with the neccesary items
*/
void AddOtherData::fillComboBoxes(){
///SCHEDULES
ui.schedulesComboBox->clear();
QList<TrainingSchedule*> list =  filehandler->getTrainingSchedules();
QStringList schedules = QStringList();
for(int i=0;i<list.size();i++){
	schedules << list.at(i)->getName();
	}
ui.schedulesComboBox->addItems(schedules);
///TRAININGS
trainingList.clear();
ui.trainingComboBox->clear();
QList<Training*> temp = filehandler->getTrainings();
QStringList trainings = QStringList();
for(int i=0;i<temp.size();i++){
	if(temp.at(i)->getDate() <= QDate::currentDate()){
		QString name = StringDate(temp.at(i)->getDate()).getQString();
		name.append(" - ");
		name.append(temp.at(i)->getTitle());
		trainings<<name;
		trainingList.append(temp.at(i));
		}
}
ui.trainingComboBox->addItems(trainings);
}


/**
 * set all the signals and slots, for the buttons in buttonlist
 */
void AddOtherData::setSignalsSlots()
{
	QObject::connect(ui.nextButton, SIGNAL(pressed()), this, SLOT(nextPressed()));
	QObject::connect(ui.cancelButton, SIGNAL(pressed()), this, SLOT(cancelPressed()));
	QObject::connect(ui.finishButton, SIGNAL(pressed()), this, SLOT(finishPressed()));
}



