/***************************************************************************
 *   Copyright (C) 2006 by Oscar Ljunggren   *
 *   oscar.ljunggren@gmail.com   *
 *                                                                         *
 *   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 "kpersonaltrainer_handler.h"
#include "exercises_handler.h"
#include "kpersonaltrainer.h"
#include "reports_handler.h"
#include <kapp.h>
#include <kdialog.h>
#include <qpushbutton.h>
#include <kconfigdialog.h>
#include <settings.h>
#include <klocale.h>
#include <qlineedit.h>
#include <qdatetime.h>
#include <kdatetbl.h>
#include <qcolor.h>
#include <qtextstream.h>
#include <qfile.h>
#include <qapplication.h>
#include <kdatewidget.h>
#include <kmessagebox.h>
#include <qlistview.h>
#include <kstandarddirs.h>


kpersonaltrainer_handler::kpersonaltrainer_handler(QWidget *parent, const char *name)
    :kpersonaltrainerview_base(parent, name)
{

	
	exerciseCombo->insertStringList(Settings::exercisesList());
	exercisesTable->setColumnWidth(0,240);
	exercisesTable->setColumnWidth(1,70);
	exercisesTable->setColumnWidth(2,100);
	exercisesTable->setColumnWidth(3,80);
	exercisesTable->setColumnWidth(5,140);
	exercisesTable->setColumnWidth(4,200);
	exercisesTable->hideColumn(6);
	exercisesTable->setSortColumn(4);
	exercisesTable->setRootIsDecorated(true);
	exercisesTable->setAllColumnsShowFocus(true);
	
	dateEdit->setDate(QDate::currentDate());
	
    		
	readFileToTable();
	
	
	
		
}
// Quit the application
void kpersonaltrainer_handler::quitButton_clicked()
{
	kapp->quit();
}

// TODO: Show diagram of the rows/colums showed
void kpersonaltrainer_handler::diagramButton_clicked()
{

}

void kpersonaltrainer_handler::addExerciseButton_clicked()
{
	//View of table Exercise,Time,AvgPulse,MaxPulse,MinPulse,Date,SplitTimes
	// If exercises or time are empty, start dialog tell them to change those.
	if(totalTimeEdit->text()=="" || exerciseCombo->currentText()=="")
		return;
	
	QDate trainingDay = dateEdit->date();
	QString id = getNextNumber();
	
	QListViewItem *addItem = new QListViewItem( exercisesTable, exerciseCombo->currentText(), totalTimeEdit->text(), avgPulseEdit->text(), maxPulseEdit->text(),trainingDay.toString(Qt::ISODate),id);
		
		for(uint i=0; i<splitTimeList->count(); i++)
			new QListViewItem (addItem, splitTimeList->item(i)->text());
		
	QString splitTimes;
				
	if(splitTimeList->count()){
		for(uint i=0; i<splitTimeList->count(); i++){
		splitTimes.append(splitTimeList->item(i)->text());
		if(splitTimeList->count()!=i+1)
			splitTimes.append('|');
		
		}
	}
	// Mark trainingDay in calendar
	dateTable->setCustomDatePainting(trainingDay,QColor(255, 255, 255),dateTable->CircleMode, QColor(0,200,0));
	
	// Save the data to a file and send it to be saved
 	QStringList exerciseData;
	exerciseData.append(id);
 	exerciseData.append(exerciseCombo->currentText());
 	exerciseData.append(totalTimeEdit->text());
 	exerciseData.append(avgPulseEdit->text());
 	exerciseData.append(maxPulseEdit->text());
 	exerciseData.append(trainingDay.toString(Qt::ISODate));
	if(splitTimeList->count())
		exerciseData.append(splitTimes);
		
	saveExerciseDataToFile(exerciseData);
	
	clearButton_clicked();
	// Delete unused pointers
	//delete sItem;
	//delete splitBox;
}	

void kpersonaltrainer_handler::newExerciseButton_clicked()
{
	manageExercises();
}

// TODO: Start the synchronization dialog
void kpersonaltrainer_handler::getData_clicked()
{
}

// TODO : Start a dialog with weekly report stuff....
void kpersonaltrainer_handler::manageReport()
{
if ( KConfigDialog::showDialog( "reports" ) ) 
		return; 
        
		KConfigDialog *reportDialog = new KConfigDialog(this, "reports", Settings::self(), KDialogBase::Swallow,KDialogBase::Ok | KDialogBase::Cancel );
		reports_handler *rep = new reports_handler();
		reportDialog->addPage(rep, i18n("Weekly Report"), "reports");
		connect(reportDialog, SIGNAL(settingsChanged()), rep, SLOT(settingsChanged()));
		reportDialog->show();


}
// FINISHED : Show a list of exercises, (need to be saved), and make a new textedit to enter new ones.
void kpersonaltrainer_handler::manageExercises()
{
if ( KConfigDialog::showDialog( "exercises" ) ) 
		return; 
        
		KConfigDialog *exDialog = new KConfigDialog(this, "exercises", Settings::self(), KDialogBase::Swallow,KDialogBase::Ok | KDialogBase::Cancel);
		exercises_handler *ex = new exercises_handler();
		exDialog->addPage(ex, i18n("Manage Exercises"), "exercises");
		connect(exDialog, SIGNAL(settingsChanged()), ex, SLOT(exercisesSettingsChanged()));
		connect(exDialog, SIGNAL(settingsChanged()), this, SLOT(settingsChanged()));
		exDialog->show();

}

// Add alla 
void kpersonaltrainer_handler::settingsChanged()
{
	exerciseCombo->clear();
	exerciseCombo->insertStringList(Settings::exercisesList());
}

void kpersonaltrainer_handler::exerciseCombo_activated(const QString&)
{
}
// FINSIHED: use a string instead of stringlist, and then make it completed directly, Time avg(pulse) max(pulse)
void kpersonaltrainer_handler::addSplitTime_clicked()
{
	QString splitData;
	
	if(!splitTimeEdit->text().isEmpty()){
		splitData.append(QString::number(splitTimeList->count()+1));
		splitData.append(". ");
		splitData.append(splitTimeEdit->text());
		if(!splitAvgPulse->text().isEmpty()){
			splitData.append("   avg(");
			splitData.append(splitAvgPulse->text());
			splitData.append(")");
			}
		if(!splitMaxPulse->text().isEmpty()){
			splitData.append(" max(");
			splitData.append(splitMaxPulse->text());
			splitData.append(")");
			}
		
	splitTimeList->insertItem(splitData);
	splitTimeEdit->clear();
	splitAvgPulse->clear();
	splitMaxPulse->clear();
	}
	
}

void kpersonaltrainer_handler::removeSplitTime_clicked()
{
	splitTimeList->removeItem(splitTimeList->currentItem());
}

void kpersonaltrainer_handler::saveExerciseDataToFile(QStringList list){
	// Data to save in the file, trainingnumber (get from file), time, avgpulse, maxpulse, date, split times, avg pulse, max pulse
	
	QString myFile = locateLocal("appdata", "exercises.data");
	QFile file(myFile);
	QTextStream stream( &file );
                
	if ( file.open( IO_WriteOnly | IO_Append ) ) {
        // should get to the end of the file
        	while ( !stream.atEnd() ) {
        	// get the last number
        		stream.readLine();
        	}
        	for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ){
			QStringList::Iterator check = it; 
			if(++check != list.end()) 
				stream << *it << "|";
			else
				stream << *it;
			}
			
		stream << "\n";
    		    	
        	file.close();
    
	}	
}

void kpersonaltrainer_handler::readFileToTable(){

	
	
	QString myFile = locateLocal("appdata", "exercises.data");
	QFile file(myFile);
	
	QTextStream stream( &file );
	if ( file.open( IO_ReadOnly ) ) {
        	QTextStream stream( &file );
        	QStringList recordList;
        	QString records;
		while ( !stream.atEnd() ) {
			records = stream.readLine(); // line of text excluding '\n'
			recordList = QStringList::split('|',records,true);
			QListViewItem *newItem = new QListViewItem( exercisesTable, recordList[1], recordList[2], recordList[3], recordList[4],recordList[5], recordList[0]);
			
			for (uint i=6; i<recordList.count(); i++)
				new QListViewItem (newItem, recordList[i]);
			
			dateTable->setCustomDatePainting(QDate::fromString(recordList[5],Qt::ISODate),QColor(255, 255, 255),dateTable->CircleMode, QColor(0,200,0));

		}
		file.close();
	}


}

// TODO Get REAL selected row in table, maybe a qdialog,("Do u really wanna delete?"), find the number, delete from file. update table.
void kpersonaltrainer_handler::deleteRow_clicked()
{
	
	if (!exercisesTable->firstChild() || exercisesTable->currentItem()->parent())
		return; 
	int reply = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the selected exercise?"),"Message", KStdGuiItem::yes(), KStdGuiItem::no());
	if (reply==4)
		return;
		
	deleteWithID(exercisesTable->currentItem()->text(5));
	exercisesTable->clear();
    	readFileToTable();
	
}

QString kpersonaltrainer_handler::getNextNumber() {
	
	
	QString numberFileString = locateLocal("appdata", "numbers.data");
	QFile numberFile(numberFileString);
	QTextStream stream( &numberFile );
        QString number;         
        int nbr = 1;
	if ( numberFile.open( IO_ReadOnly ) ) {
               	number = stream.readLine();
               	nbr = number.toInt();
        	if (nbr==0){
        		nbr = 1;
        	}
        	else
			nbr++;
		  		    	
	numberFile.close();
    	}	
    	if ( numberFile.open( IO_WriteOnly ) ) {
		stream << nbr;   	
    	}
    	
	return QString::number(nbr);
}
// FINISHED Make the split fields editable :)
void kpersonaltrainer_handler::editSplitData_clicked()
{
	
	splitTimeEdit->setEnabled(true);
	splitAvgPulse->setEnabled(true);
	splitMaxPulse->setEnabled(true);
	splitTimeList->setPaletteBackgroundColor(QColor(255,255,255));
	addSplitTime->setEnabled(true);
	removeSplitTime->setEnabled(true);
}

// TODO save the ID, send all other values to fields, remove the ID to the field. (then by pressing the add buttons everything will run normally)
void kpersonaltrainer_handler::editExerciseButton_clicked()
{
	if (!exercisesTable->firstChild())
		return; 
			
	clearButton_clicked();
	QListViewItem *editItem = exercisesTable->currentItem();
	
	if (editItem->parent())
		return; 
		
	exerciseCombo->setCurrentText(editItem->text(0));
	totalTimeEdit->setText(editItem->text(1));
	avgPulseEdit->setText(editItem->text(2));
	maxPulseEdit->setText(editItem->text(3));
	QDate currentDate = QDate::fromString(editItem->text(4),Qt::ISODate);
	dateEdit->setDate(currentDate);
		
	if(editItem->firstChild()){
		editSplitData_clicked();
		editItem = editItem->firstChild();
		while(editItem) {
            		splitTimeList->insertItem(editItem->text(0));
            		editItem = editItem->nextSibling();
        	}
// 	

	}
	deleteWithID(exercisesTable->currentItem()->text(5));
	exercisesTable->takeItem(exercisesTable->currentItem());

}

void kpersonaltrainer_handler::deleteWithID(QString idNbrString) {

QStringList linesExceptDeleted, test;
	
	QString myFile = locateLocal("appdata", "exercises.data");
	QFile file(myFile);
    	
    	if ( file.open( IO_ReadOnly ) ) {
	        QTextStream stream( &file );
	        QString line;
	        while ( !stream.atEnd() ) {
			line = stream.readLine();
			test = QStringList::split('|',line,false);
			if(test[0].compare(idNbrString)){
				linesExceptDeleted += line;
				}
        	}
	file.close();
    	}
	
    	if ( file.open( IO_WriteOnly ) ) {
        QTextStream stream( &file );
        for ( QStringList::Iterator it = linesExceptDeleted.begin(); it != linesExceptDeleted.end(); ++it )
            stream << *it << "\n";
        file.close();
    }
    

}

void kpersonaltrainer_handler::clearButton_clicked()
{
	totalTimeEdit->clear();
	avgPulseEdit->clear();
	maxPulseEdit->clear();	
	splitTimeEdit->clear();
	splitAvgPulse->clear();
	splitMaxPulse->clear();
	splitTimeList->clear();
	
}



void kpersonaltrainer_handler::dateTable_dateChanged(QDate selectedDate)
{
	dateEdit->setDate(selectedDate);
}





	
#include "kpersonaltrainer_handler.moc"
