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

Grid::Grid(QWidget *parent, ConfigFileHandlerPowerTraining *filehandler)
     : QWidget(parent)
{
     	ui.setupUi(this);
	this->filehandler = filehandler;
	busytabling=true;
	buildGui();

}

/**
*Builds the gui and sets the signals/slots
*/
void Grid::buildGui(){
	tab1Content = new TableWidgetOfTestData(this,filehandler);
	QObject::connect(tab1Content,SIGNAL(someCellChanged()),this,SLOT(someValueChanged()));

	ui.vboxLayout1->addWidget(tab1Content);
	ui.startDateEdit->setDate(QDate::currentDate().addDays(-30));
	ui.endDateEdit->setDate(QDate::currentDate());

	ui.tableWidget2->setColumnCount(5);
	ui.tableWidget2->setColumnWidth(0,40);

	QObject::connect(ui.scheduleComboBox,SIGNAL(currentIndexChanged(QString)),this, SLOT(scheduleChanged(QString)));
	QObject::connect(ui.startDateEdit,SIGNAL(dateChanged(QDate)),this,SLOT(dateChanged(QDate)));
	QObject::connect(ui.endDateEdit,SIGNAL(dateChanged(QDate)),this,SLOT(dateChanged(QDate)));

	QObject::connect(ui.listWidget,SIGNAL(currentRowChanged(int)),this,SLOT(currentScheduleOcChanged(int)));
	QObject::connect(ui.tableWidget2,SIGNAL(cellChanged(int,int)),this,SLOT(cellChanged(int,int)));

	QObject::connect(ui.printButton, SIGNAL(pressed()),this,SLOT(printScheduleOccurrence()));

	scheduleChanged(ui.scheduleComboBox->currentText());

	///TODO: fix printing support:
	ui.printButton->hide();
}

/**
*Emits updateVisualisation();
*/
void Grid::someValueChanged(){
emit updateVisualisation();
}

/**
*This method prints the currently displayed schedule occurrence (second tab grid)
*/
void Grid::printScheduleOccurrence(){
//TODO///printing isn't working

QPrinter *printer = new QPrinter( );
QPrintDialog dlg(printer, this);
if (dlg.exec() == QDialog::Accepted)
/*
QPrinter *printer = new QPrinter( );
QPrintDialog printDialog(printer, 0);
QPixmap imageToPrint = QPixmap::grabWidget(ui.tableWidget2);
if( printDialog.exec() == QDialog::Accepted )*/
{
    // calculate the total width/height table would need without scaling
    const int rows = ui.tableWidget2->model()->rowCount();
    const int cols = ui.tableWidget2->model()->columnCount();
    double totalWidth = 0.0;
    for (int c = 0; c < cols; ++c)
    {
        totalWidth += ui.tableWidget2->columnWidth(c);
    }
    double totalHeight = 0.0;
    for (int r = 0; r < rows; ++r)
    {
        totalHeight += ui.tableWidget2->rowHeight(r);
    }
 
    // redirect ui.tableWidget2's painting on a pixmap
    QPixmap pixmap(totalWidth, totalHeight);
    QPainter::setRedirected(ui.tableWidget2, &pixmap);
    // print scaled pixmap
    QPainter painter(printer);
    painter.drawPixmap(printer->pageRect(), pixmap, pixmap.rect());


/*

	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( ) );*/
} 

}


/**
*The user selected another ScheduleOc from the list
*/
void Grid::currentScheduleOcChanged(int selection){
busytabling=true;
int i=ui.tableWidget2->rowCount(); while(i !=0){i--; ui.tableWidget2->removeRow(ui.tableWidget2->rowCount()-1);}
if(selectedScheduleOccurrenceList.size()>selection-1 && selection>=0){
ScheduleOccurrence So = selectedScheduleOccurrenceList.at(selection);
TrainingSchedule *trainingSchedule = filehandler->getTrainingSchedule(So.getName());

	int index=0;
	ui.tableWidget2->setColumnCount(5);
	ui.tableWidget2->setColumnWidth(0,40);
	///->setColumnWidth(1,200);
	QBrush brush = QBrush(Qt::lightGray, Qt::SolidPattern);
	for(int rot=0;rot<trainingSchedule->getNumberOfRotations();rot++){
		int totIterations = trainingSchedule->getNumberOfTimesExerciseIsRepeatedInARotation(rot);
		for(int i=0; i<filehandler->getExercise()->getNbOfExercises();i++){
			int index = filehandler->getExercise()->getIndexes().at(i);
			Exercise *ex = filehandler->getExercise()->getExercise(index);
			if(So.getExercises().contains(ex->getName())){
				for(int iter=0;iter<totIterations;iter++){
				int row = ui.tableWidget2->rowCount();
				ui.tableWidget2->insertRow(row);
				ui.tableWidget2->takeVerticalHeaderItem(row);
				QTableWidgetItem *itemSet = new QTableWidgetItem();
				QString set; set.setNum(rot+1);
				itemSet->setText(set);
				itemSet->setFlags(Qt::ItemIsEnabled);
				//itemSet->setBackground(brush);
				ui.tableWidget2->setItem(row,0,itemSet);

				QTableWidgetItem *itemExercise = new QTableWidgetItem();
				itemExercise->setText(filehandler->getExercise()->getName(i));
				itemExercise->setFlags(Qt::ItemIsEnabled);
				//itemExercise->setBackground(brush);
				ui.tableWidget2->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.tableWidget2->setItem(row,4,itemPerformance);

				QTableWidgetItem *itemRepetitions = new QTableWidgetItem();
				QString repetitionsS;
				repetitionsS.setNum(So.getRepetitions().at(index));
				itemRepetitions->setText(repetitionsS);
				itemRepetitions->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable |Qt::ItemIsEnabled);
				//itemRepetitions->setBackground(brush);
				ui.tableWidget2->setItem(row,3,itemRepetitions);

				QTableWidgetItem *itemWeight = new QTableWidgetItem();
				QString weightS;
				weightS.setNum(So.getWeights().at(index));
				itemWeight->setText(weightS);
				itemWeight->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable |Qt::ItemIsEnabled);
				ui.tableWidget2->setItem(row,2,itemWeight);
				index++;
				}
			}
		}
	}

}
busytabling=false;
}

/**
*SLOT: new schedule was selected => update schedule-occurrence-list!
*/
void Grid::scheduleChanged(QString newschedule){
selectedScheduleOccurrenceList.clear();
int i=ui.tableWidget2->rowCount(); while(i !=0){i--; ui.tableWidget2->removeRow(ui.tableWidget2->rowCount()-1);}
StringDate date1 = StringDate(ui.startDateEdit->date()); ///old date
StringDate date2 = StringDate(ui.endDateEdit->date()); ///recent date
StringDate dateIterator = date2;
while(date1 <= dateIterator){
	if(filehandler->containsScheduleOccurrences(dateIterator.getQString())){
		QList<ScheduleOccurrence> *temp = filehandler->getScheduleOccurrences(dateIterator.getQString());
		for(int i=0;i<temp->size();i++){
			if(temp->at(i).getName() == newschedule){
				selectedScheduleOccurrenceList.append(temp->at(i));
				}
			}
		}
	dateIterator.addDays(-1);
	}
updateSelectedScheduleOcList();

}

/**
*update the listWidget to represent the given selected scheduleOCs
*/
void Grid::updateSelectedScheduleOcList(){
ui.listWidget->clear();
QStringList names = QStringList();
for(int i=0;i<selectedScheduleOccurrenceList.size();i++){
	QString name = selectedScheduleOccurrenceList.at(i).getName();
	name.append(" - ");
	name.append(StringDate(selectedScheduleOccurrenceList.at(i).getDate()).getQString());
	names<<name;
	}
ui.listWidget->addItems(names);
}

/**
*SLOT: normally triggered when some schedule was changed, 
* this means scheduleOcs where deleted, this means reloading the date
*/
void Grid::reloadOtherScheduleOccurrences(){
ui.scheduleComboBox->clear();
ui.listWidget->clear();
int i=ui.tableWidget2->rowCount(); while(i !=0){i--; ui.tableWidget2->removeRow(ui.tableWidget2->rowCount()-1);}

QStringList schedules = QStringList();
for(int i=0;i<filehandler->getTrainingSchedules().size();i++){
	schedules<<filehandler->getTrainingSchedules().at(i)->getName();
	}
ui.scheduleComboBox->addItems(schedules);
}


/**
*SLOT date changed from one of enDate/startDate
*/
void Grid::dateChanged(QDate newselection){
scheduleChanged(ui.scheduleComboBox->currentText());
}

/**
*Load all profile dependent information
*/
void Grid::loadsettings(ConfigFileHandlerPowerTraining *filehandler)
{
this->filehandler=filehandler;
tab1Content->loadsettings(filehandler);
reloadOtherScheduleOccurrences();/*
ui.scheduleComboBox->clear();
ui.listWidget->clear();
int i=->rowCount(); while(i !=0){i--; ->removeRow(->rowCount()-1);}

QStringList schedules = QStringList();
for(int i=0;i<filehandler->getTrainingSchedules().size();i++){
	schedules<<filehandler->getTrainingSchedules().at(i)->getName();
	}
ui.scheduleComboBox->addItems(schedules);*/
}

/**
*redraw, reason may be: datapoints added
*/
void Grid::redraw(){
tab1Content->redraw();
}

/**
*redraw data from exercise with index i, reason may be: datapoints added
*/
void Grid::redraw( int i){
tab1Content->redraw(i);
}

/**
*This slot saves the new values in the profile.
*/
void Grid::cellChanged(int row ,int collumn){
if(!busytabling){
	int selection = ui.listWidget->currentRow();
	if(selectedScheduleOccurrenceList.size()>selection-1 && selection>=0){
		ScheduleOccurrence So = selectedScheduleOccurrenceList.at(selection);
		if(collumn==2){
			///weight
			int newWeight = ui.tableWidget2->item(row,collumn)->text().toInt();
			QList<int> temp = So.getWeights();
			temp.replace(row,newWeight);
			So.setWeights(temp);
			filehandler->addScheduleOccurrence(&So);

			QMessageBox msgBox;
			msgBox.setIcon(QMessageBox::Information);
			msgBox.setStandardButtons(QMessageBox::Ok);
			msgBox.setText(tr("Datapoint was edited and saved into the QProfile"));
			msgBox.exec();

			
			}

		if(collumn==3){
			///repetitions
			int newRep = ui.tableWidget2->item(row,collumn)->text().toInt();
			QList<int> temp = So.getRepetitions();
			temp.replace(row,newRep);
			So.setRepetitions(temp);
			filehandler->addScheduleOccurrence(&So);

			QMessageBox msgBox;
			msgBox.setIcon(QMessageBox::Information);
			msgBox.setStandardButtons(QMessageBox::Ok);
			msgBox.setText(tr("Datapoint was edited and saved into the QProfile"));
			msgBox.exec();
			
			}
	///Also change the copy of the ScheduleOc that is kept in Grid
	StringDate date = StringDate(So.getDate());
	for(int i=0;i<selectedScheduleOccurrenceList.size();i++){
		if(selectedScheduleOccurrenceList.at(i).getDate()==So.getDate() && selectedScheduleOccurrenceList.at(i).getName()==So.getName()){
			selectedScheduleOccurrenceList.replace(i,So);
			}
		}
	}


}
}

