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

TrainScheduleDisplayer::TrainScheduleDisplayer(QWidget *parent)
     : QWidget(parent)
 {
     	ui.setupUi(this);
	QObject::connect(ui.PrintButton,SIGNAL(pressed()), this, SLOT(print()));
	numberOfExercises = 0;
	numberOfCharacters =0;
	numberOfSchedules = 0;
	schedule=new TrainingSchedule();
}

/**
*Prints all the Schedules set in this Training.as HTML
*/
void TrainScheduleDisplayer::setTraining(Training *training, ConfigFileHandlerPowerTraining *filehandler){
	QString text="<html>  <head>  <title>";
	text.append(training->getTitle());
	text.append("</title></head><body>");
	text.append("<H1>"+training->getTitle()+"</H1>");
	text.append(training->getExplaination());
	numberOfCharacters+=training->getExplaination().size();
	
	for(int i=0; i<training->getOrderList().size();i++){ ///loop over all schedules of the training
		QStringList list = QStringList(training->getTrainingSchedulesMap().value(training->getOrderList().at(i)));
		///list of all its exercises
		text = addSchedule(text,training->getOrderList().at(i),filehandler,list, false);
	}

/*

	for(int i=0; i<training->getOrderList().size();i++){
		QStringList list = QStringList(training->getTrainingSchedulesMap().value(training->getOrderList().at(i)));
		QList<int> list_ints = QList<int>();
		for(int i=0;i<list.size();i++){
			int index = filehandler->getExercise()->getindex(list.at(i));
			if(index!=-1){list_ints.append(index);}
			}
		text = addSchedule(text,training->getOrderList().at(i),filehandler,list_ints, false);
	}*/

// 	QMapIterator<QString, QStringList> iter(training->getTrainingSchedulesMap());
//  	while (iter.hasNext()) {
//      		iter.next();
// 		QStringList list = QStringList(iter.value());
// 		QList<int> list_ints = QList<int>();
// 		for(int i=0;i<list.size();i++){
// 			int index = filehandler->getExercise()->getindex(list.at(i));
// 			if(index!=-1){list_ints.append(index);}
// 			}
// 		text = addSchedule(text,iter.key(),filehandler,list_ints);
//  	}
	ui.textBrowser->setHtml(text);
	text.append("</body> </html>");
}

/**
*adds a schedule to the given string
*/
QString TrainScheduleDisplayer::addSchedule(QString text, QString schedulename, ConfigFileHandlerPowerTraining *filehandler, QList<QString> allowedExercisesList, bool resetNbOfExercisesAndCharactersAndSchedules){
if(resetNbOfExercisesAndCharactersAndSchedules){numberOfExercises=0; numberOfCharacters=0; numberOfSchedules=0;}
numberOfSchedules++;

bool schedulefound=false; //if we don't find a schedule with the given name...
	
	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){
		schedule=list.at(i);
		schedulefound=true;
		}
	}

	if(!schedulefound){text.append("<h2>Schedule Not Found</h2>");}

	else{
	
	///we need to know this for setting size of printer.
	//numberOfExercises = filehandler->getExercise()->getNameList().size(); 
	///for adapting programs
	text.append("<H2>"+schedulename+"</H2>");
	text.append(schedule->getExplaination());
	numberOfCharacters+=schedule->getExplaination().size();
		
	text.append(" <table border=\"1\" cellpadding=\"5\" cellspacing=\"0\"> <tbody> ");
	text.append(tr("<tr  margin-left=\"1\" bgcolor=\"Silver\"><td> <strong>Set:</strong></td>"));
	text.append(tr("<td> <strong>Exercise:</strong></td>"));
	text.append(tr("<td> <strong>Suggested Weight:</strong></td>"));
	text.append(tr("<td> <strong>Repetitions:</strong></td>"));
	text.append(tr("<td> <strong>Weight I Used:</strong></td>"));
	text.append(tr("<td> <strong>Repetitions I Did:</strong></td></tr>"));

/*
comment jorrit: wouldn't it be better to print "weight used" and "repetitions done" to save both inkt and space? :-)
*/
	
	int totRot = schedule->getNumberOfRotations();

	for(int rot=0;rot<totRot;rot++){
		int totIterations = schedule->getNumberOfTimesExerciseIsRepeatedInARotation(rot);
		for(int i=0; i<allowedExercisesList.size();i++){
			for(int iter=0;iter<totIterations;iter++){
				QString name = allowedExercisesList.at(i);
				int a = schedule->getNumberOfTimesExerciseIsDone(rot,iter);
				int b = schedule->getPerformance(rot,iter);
				text = addExcercise(text, rot, name,a,b,filehandler);
				}
			}
		}
	



	/*
	for(int rot=0;rot<totRot;rot++){
		int totIterations = schedule->getNumberOfTimesExerciseIsRepeatedInARotation(rot);
		for(int i=0; i<filehandler->getExercise()->getNbOfExercises();i++){
			if(allowedExercisesList.contains(i)){
				for(int iter=0;iter<totIterations;iter++){
				text = addExcercise(text, rot, filehandler->getExercise()->getName(i),schedule->getNumberOfTimesExerciseIsDone(rot,iter),schedule->getPerformance(rot,iter),filehandler);
				}
			}
		}
	}
	*/

	text.append("</tbody> </table>");
	}
	return text;
}

/**
*Sets the schedule to 'schedulename' and prints all exercises as HTML
*@param allowedExercisesList are names of exercises that are allowed to be shown.
*/
void TrainScheduleDisplayer::setSchedule(QString schedulename, ConfigFileHandlerPowerTraining *filehandler, QList<QString> allowedExercisesList)
{
	numberOfExercises=0;
	numberOfCharacters=0;
	numberOfSchedules=0;
	QString text="<html>  <head>  <title>";
	text.append(schedulename);
	text.append("</title></head><body>");
	text.append(addSchedule(text,schedulename,filehandler,allowedExercisesList));
	ui.textBrowser->setHtml(text);
	text.append("</body> </html>");
}

/**
 * adds an excersise <excersise> to the program (text), and uses data from the profile
 * @param text html String that gets expanded
 * @param Rotation number of rotation (started counting from 1)
 * @param excersisename name of exercis
 * @return 
 */
QString TrainScheduleDisplayer::addExcercise(QString text, int rotation, QString exercisename, int repetitions, int performance, ConfigFileHandlerPowerTraining *filehandler)
{
numberOfExercises++;

float performancefloat=(100.0-performance)/100;
float newrepetitions = repetitions;
if(performance >=0 && performance <100){
	newrepetitions = repetitions+repetitions*performancefloat;
}
///less effort => calculate a weight that would normally be used to do more repetitions then the one needed to do


QString num;
num.setNum(rotation+1);
text.append(QString("<tr><td>")+num+QString("</td>"));
text.append(QString("<td> <strong>")+exercisename+QString(": </strong></td>"));

QList<PowerTrainingMeasurement *> list = filehandler->getExercise()->getExercise(exercisename)->getMeasurements();
if(list.size()>0){
	float weightToUse = list.at(list.size()-1)->getNormalisedWeight();
	int weightToUseInt = (weightToUse);
	num.setNum(weightToUseInt);
	num.append(" Kg");
	}

// if(latestweight!=0){
// 	float weightToUse = filehandler->getExercise()->getExercise(exercisename)->getMeasurements() filehandler->normalize(latestweight,filehandler->getDefaultValueForRepetitions(),newrepetitions);
// 	int weightToUseInt = (weightToUse);
// 	num.setNum(weightToUseInt);
// 	num.append(" Kg");
// 	}
else {
	num=tr("?");
	}
text.append("<td>"+num+"</td>");

num.setNum(repetitions);
QString timeortimes=tr(" Times");
if(repetitions==1){timeortimes=tr(" Time");}
text.append("<td>"+num+timeortimes+"</td></tr>");
	
return text;
}


/**
 * Print the current schedule
 */
void TrainScheduleDisplayer::print()
{
///set height of printed Qtextbrowser...otherwise he will print it with a slider...
///one character = 0.2 pixels in height (100 characters per line of 20px)
float heightf = 60.0+40.0*numberOfExercises+0.2*numberOfCharacters+90.0*numberOfSchedules;
int height = (int)heightf;
printer = new QPrinter( );
QPrintDialog printDialog(printer, 0);
QTextBrowser *widget = new QTextBrowser();
widget->hide();
widget->setHtml(ui.textBrowser->toHtml());
widget->setFixedSize(1000,height);
widget->setFrameShape(QFrame::NoFrame);
widget->setFrameShadow(QFrame::Plain);
QPixmap imageToPrint = QPixmap::grabWidget(widget);
if( printDialog.exec() == QDialog::Accepted )
{
	QPainter painter(printer);
        QRect rect = painter.viewport( );
     	QSize size = imageToPrint.size( );
     
	size.scale( rect.size( ), Qt::KeepAspectRatio );
     	painter.setViewport( rect.x( ), rect.y( ), size.width( ), size.height( ) );
     	painter.setWindow( imageToPrint.rect( ) );
     	painter.drawImage( 0, 0, imageToPrint.toImage( ) );
} 
}
