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

AddExerciseDialog::AddExerciseDialog(QWidget *parent, ConfigFileHandlerPowerTraining *filehandler)
     : QWidget(parent)
 {
	ui.setupUi(this);
	ui.textEdit_2->setReadOnly(true);

	this->filehandler = filehandler;
	
	itemList = new QList<QListWidgetItem*>(); ///list to keep the Items representing the search result;
	muscleList = new QList<QListWidgetItem*>(); ///same as itemlist, so we can delete all items easely;

	tab2Concent = new OneExercise(ui.tab2, 0, filehandler->getExercise()->getPossibleMuscleList(),filehandler->getExercise()->getPossibleExerciseTagList());
	tab2Concent->setNewExercise(true);
	ui.vboxLayout4->addWidget(tab2Concent);
	QObject::connect(tab2Concent,SIGNAL(saveExercise(QString, QString, QStringList,QString)),this,SLOT(addExercise1(QString, QString, QStringList, QString)));
	QObject::connect(tab2Concent,SIGNAL(addTag(QString)), this, SLOT(addTag(QString)));
	QObject::connect(tab2Concent,SIGNAL(closeParent2()), this, SLOT(close()));
	QObject::connect(ui.listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(itemWasClicked(QListWidgetItem*)));
//	QObject::connect(ui.addButton1,SIGNAL(pressed()), this, SLOT(addExercise1()));
	QObject::connect(ui.addButton2,SIGNAL(pressed()), this, SLOT(addExercise2()));
	QObject::connect(ui.searchButton,SIGNAL(pressed()), this, SLOT(search()));
	
	QObject::connect(filehandler->getExercise(),SIGNAL(exerciseTagListChanged(QStringList)),tab2Concent,SLOT(reloadTagList(QStringList)));
	
	fillComboBoxes();
	//tab2Concent->setAutoSaveFunctionOn();
}

/**
*adds an exercisetag to the QProfile
*/
void AddExerciseDialog::addTag(QString tag){
filehandler->getExercise()->addExerciseTag(tag);
tab2Concent->setTag(tag);

emit exerciseTagListChanged();
}

/**
*execute when new profile is opened.
*fill the possible tag-list in de comboBox
*/
void AddExerciseDialog::loadsettings(ConfigFileHandlerPowerTraining *filehandler){
	this->filehandler=filehandler;
	tab2Concent->reloadTagList(filehandler->getExercise()->getPossibleExerciseTagList());
}

void AddExerciseDialog::fillComboBoxes()
{
///exercises
QStringList  list = QStringList(filehandler->getExercise()->getPossibleMuscleList());
//ui.comboBox1->addItems(list);
ui.comboBox2->addItems(list);

///language not a good way of doing it!
ui.comboBox3->addItem("English");
ui.comboBox3->addItem("Dutch");
ui.comboBox3->addItem("French");
ui.comboBox3->addItem("Other");


}

/**
 * this slot is called when add exercise button is pressed. We add the exercise selected in the current tab.
 * first tab widget (manually added)
 */
void AddExerciseDialog::addExercise1(QString name, QString explaination, QStringList muscles, QString tag){
filehandler->addExercise(name,explaination,muscles,tag);
emit exerciseAdded();
///tel the user the exercise was added
 		QMessageBox msgBox;
 		msgBox.setStandardButtons(QMessageBox::Ok);
 		msgBox.setText(tr("The exercise has been added to your profile."));
 		switch (msgBox.exec()) 
 			{
 			case QMessageBox::Ok:
 			//ok
 			break;
 			default:
      			// should never be reached
      			break;
  			}
}

/**
 * this slot is called when add exercise button is pressed. We add the exercise selected in the current tab.
 * automaticly added
 */
void AddExerciseDialog::addExercise2()
{
///Second tab is selected
	QString name = ui.listWidget->currentItem()->text();
	QString explaination = ui.textEdit_2->toPlainText();
	QStringList muscles = QStringList();
	for(int i =0;i<ui.listWidget_2->count();i++){
	muscles<<ui.listWidget_2->item(i)->text();
	}
	filehandler->addExercise(name,explaination,muscles);
	emit exerciseAdded();
		///tel the user the exercise was added
		QMessageBox msgBox;
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setText(tr("The exercise has been added to your profile."));
		switch (msgBox.exec()) 
			{
			case QMessageBox::Ok:
			//ok
			break;
			default:
     			// should never be reached
     			break;
 			}
}

/**
*search for exercise online (using XML-RPC)
*/
void AddExerciseDialog::search()
{
///clear discriptionlist
ui.textEdit_2->setText("");
///remove old search result
itemList->clear();
muscleList->clear();
ui.listWidget->clear(); //names 
ui.listWidget_2->clear(); //musclenames


QSettings settings("ToonSoft", "Qtrainer");
settings.beginGroup("ProgramSettings");
QString url = settings.value("DatabaseURL").toString();
settings.endGroup();

myClient = new QxtXmlRpcClient(QUrl(url));

QObject::connect(myClient, SIGNAL(finished(int,QVariant)),this,SLOT(finished1(int,QVariant)));
QObject::connect(myClient, SIGNAL(fault(int,int,QString)),this,SLOT(fault(int,int,QString)));
QObject::connect(myClient, SIGNAL(parseError(int,QString)),this,SLOT(parseError(int,QString)));
QObject::connect(myClient, SIGNAL(networkError(int,QString)),this,SLOT(networkError(int,QString)));
QList<QVariant> params;
QString musclename = ui.comboBox2->currentText().section(" (",0,0);
QString exercisename = ui.lineEditName2->text();
QString explaination = ui.lineEditDescription->text();
params<<exercisename<<explaination<<musclename;
int i = myClient->call(QString("searchexercise"), params);
//QObject::disconnect(myClient, SIGNAL(finished(int,QVariant)),this,SLOT(finished1(int,QVariant)));
}

void AddExerciseDialog::fault(int callId, int faultCode, QString faultString){
	QMessageBox msgBox;
	msgBox.setStandardButtons(QMessageBox::Ok);
	msgBox.setText(tr("Something went wrong.\n")+faultString);
	msgBox.exec();
}


void AddExerciseDialog::parseError(int callId, QString errorMsg){
QMessageBox msgBox;
	msgBox.setIcon(QMessageBox::Critical);
	msgBox.setStandardButtons(QMessageBox::Ok);
	msgBox.setText(tr("A parse error occured.\nThis is probably Qtrainer's fault."));
	msgBox.exec();
}

void AddExerciseDialog::networkError(int callId, QString errorMsg){
	QMessageBox msgBox;
	msgBox.setIcon(QMessageBox::Critical);
	msgBox.setStandardButtons(QMessageBox::Ok);
	msgBox.setText(tr("A network error occured."));
	msgBox.exec();
}

/**
*finished slot for executing searchexercise (returns exercisenames)
*/
void AddExerciseDialog::finished1(int callId, QVariant retValue){
QString returnValue = retValue.toString();
int i=1;
while((returnValue.section('!',i,i)).size()>0)
	{
		addToItemList(returnValue.section('!', i, i));
		i++;
	}
//QTextStream cout(stdout, QIODevice::WriteOnly);
//cout<<retValue.toString()<<endl;
}


/**
*finished slot for executing searchexplaination (returns explaination)
*/
void AddExerciseDialog::finished2(int callId, QVariant retValue){
QString returnValue = retValue.toString();
ui.textEdit_2->setText(returnValue);
//QTextStream cout(stdout, QIODevice::WriteOnly);
//cout<<retValue.toString()<<endl;
}

/**
*finished slot for executing searchmuscle (returns musclenames)
*/
void AddExerciseDialog::finished3(int callId, QVariant retValue){
QString returnValue = retValue.toString();
int i=1;
while((returnValue.section('!',i,i)).size()>0)
	{
		addToMuscleList(returnValue.section('!', i, i));
		i++;
	}
}


/**
 * Search results are added to the ItemList
 * @param name 
 */
void AddExerciseDialog::addToItemList(QString name)
{
itemList->append(new QListWidgetItem(name,ui.listWidget));
}

/**
 * MuscleNames are added to the MuscleList
 * @param name 
 */
void AddExerciseDialog::addToMuscleList(QString name)
{
muscleList->append(new QListWidgetItem(name,ui.listWidget_2));
}

/**
 * We display the discription for the selected item.
 * @param  
 */
void AddExerciseDialog::itemWasClicked(QListWidgetItem *item)
{
muscleList->clear();
ui.listWidget_2->clear();

QSettings settings("ToonSoft", "Qtrainer");
settings.beginGroup("ProgramSettings");
QString url = settings.value("DatabaseURL").toString();
settings.endGroup();

myClient = new QxtXmlRpcClient(QUrl(url));

QObject::connect(myClient, SIGNAL(finished(int,QVariant)),this,SLOT(finished2(int,QVariant)));
QObject::connect(myClient, SIGNAL(fault(int,int,QString)),this,SLOT(fault(int,int,QString)));
QObject::connect(myClient, SIGNAL(parseError(int,QString)),this,SLOT(parseError(int,QString)));
QObject::connect(myClient, SIGNAL(networkError(int,QString)),this,SLOT(networkError(int,QString)));
QList<QVariant> params;
QString exercisename = item->text();
params<<exercisename;
int i = myClient->call(QString("searchexplaination"), params);
//QObject::disconnect(myClient, SIGNAL(finished(int,QVariant)),this,SLOT(finished2(int,QVariant)));
myClient = new QxtXmlRpcClient(QUrl(url));
QObject::connect(myClient, SIGNAL(finished(int,QVariant)),this,SLOT(finished3(int,QVariant)));
i = myClient->call(QString("searchmuscle"), params);
}

