/***************************************************************************
                          fileread.cpp  -  description
                             -------------------
    begin                : Wed May 23 2001
    copyright            : (C) 2001 by Javier Campos
    email                : javi_cms@terra.es
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "fileread.h"

#include <klocale.h>
#include <kio/job.h>
#include <kio/netaccess.h>
#include <kstandarddirs.h>

#include <qtextstream.h>
#include <qfile.h>
#include <qfileinfo.h>

#include <iostream.h>

FileRead::FileRead()
{
}

FileRead::~FileRead()
{
}

/** Open keduca file. This function can open a remote or local url. */
bool FileRead::openFile( const KURL &url )
{
	QDomDocument doc("document.xml");
//	QFilename.setName( url.url() );

	QFile QFilename;
	QFilename.setName( url.directory(false,true)+url.fileName() );


	if(!QFilename.open(IO_ReadOnly))
		{
		return false;
		}
	doc.setContent( &QFilename );

	if( doc.doctype().name() != "educa" )
		{ return false; }

	currentURL = url;

	QDomElement docElem = doc.documentElement();
	QDomNode n = docElem.firstChild();

	QDomNodeList dnList = n.childNodes();
	for( unsigned int i = 0; i < dnList.count(); ++i)
	{
		// ------------------- INFORMATION BODY -----------------------
		QDomElement element = dnList.item(i).toElement();
		if( element.tagName() == "default" || element.tagName() == "author" )
			{
			if( element.tagName() == "default" ) {	Header.insert( "image", element.attribute( "image", "default.png" ) ); }
			if( element.tagName() == "author" )	{
					QDomNodeList AuthordnList = element.childNodes();
					for( unsigned int i = 0; i < AuthordnList.count(); ++i) {
							QDomElement authorelement = AuthordnList.item(i).toElement();
							Header.insert( authorelement.tagName(), authorelement.text() );
																																	}
																					}
			} else {
			Header.insert( element.tagName(), element.text() );
			}
	}

  n = n.nextSibling();

	dnList = n.childNodes();
	for( unsigned int i = 0; i < dnList.count(); ++i)
	{
		insertQuestion();
	// --------------------- QUESTION ATTRIBUTE------------------------
		QDomElement elementNODE = dnList.item(i).toElement();
		setQuestion( QF_type, 		elementNODE.attribute( "type", "1" ).toInt() );
		setQuestion( QF_picture, 	elementNODE.attribute( "image", "" ) );
		setQuestion( QF_time, 		elementNODE.attribute( "time", "0" ).toInt() );
		setQuestion( QF_points, 	elementNODE.attribute( "points", "0" ).toInt() );

		QDomNodeList quList = elementNODE.childNodes();
		for( unsigned int x = 0; x < quList.count(); ++x)
		{
		// --------------------- QUESTION AND RESPONSES------------------
			QDomElement element = quList.item(x).toElement();
			if( element.tagName() == "text" ) 		setQuestion( QF_text, element.text() );
			if( element.tagName() == "true" )		setAnswer( element.text(), true, element.attribute( "points", "0" ).toInt() );
			if( element.tagName() == "false" )		setAnswer( element.text(), false,element.attribute( "points", "0" ).toInt() );
			if( element.tagName() == "tip" ) 			setQuestion( QF_tip, element.text() );
			if( element.tagName() == "explain" ) 	setQuestion( QF_explain, element.text() );
		}
	}

	QFilename.close();
	return true;
}

/** Set value to questions fields */
void FileRead::setQuestion( int Field, QString text)
{
// QF_text, QF_picture, QF_type, QF_time, QF_tip, QF_explain
	switch( Field )
	{
		case QF_text:
			(*RecordQuestions).Text = text;
			break;
		case QF_picture:
			(*RecordQuestions).Picture = text;
			break;
		case QF_tip:
			(*RecordQuestions).Tip = text;
			break;
		case QF_explain:
			(*RecordQuestions).Explain = text;
			break;
	}
}

/** Set value to questions fields */
void FileRead::setQuestion( int Field, int value )
{
	switch( Field )
	{
		case QF_type:
			(*RecordQuestions).Type = value;
			break;
		case QF_time:
			(*RecordQuestions).Time = value;
			break;
		case QF_points:
			(*RecordQuestions).Points = value;
			break;
	}
}

/** Insert an answer field */
void FileRead::setAnswer( QString text, bool value, int points)
{
	Answers tmpAnswers;

	tmpAnswers.Text = text;
	tmpAnswers.Value = value;
	tmpAnswers.Points = points;

	(*RecordQuestions).listAnswers.append( tmpAnswers );
}

/** Insert a blank question */
void FileRead::insertQuestion()
{
	Questions tempQuestions;
	tempQuestions.Text = "";
	listQuestions.append( tempQuestions );
	recordLast();
}

/** Go to the First record */
void FileRead::recordFirst()
{
	if( fileEOF = true ) fileEOF = false;
	if( fileBOF = false ) fileBOF = true;
	RecordQuestions = listQuestions.begin();
}

/** Go to the Last Record */
void FileRead::recordLast()
{
	if( fileBOF = true ) 	fileBOF = false;
	if( fileEOF = false ) fileEOF = true;
	RecordQuestions = listQuestions.end();
	--RecordQuestions;
}

/** Record Next */
void FileRead::recordNext()
{
	++RecordQuestions;
	if( RecordQuestions == listQuestions.end() )
		{
		fileEOF = true;
		--RecordQuestions;
		}
		else
		{
		if( fileBOF = true ) fileBOF = false;
		}
}

/** Record previous */
void FileRead::recordPrevious()
{
	if( RecordQuestions == listQuestions.begin() )
		{
		fileBOF = true;
		}
		else
		{
		if( fileEOF = true ) fileEOF = false;
		--RecordQuestions;
		}
}

/** Go to the First record */
void FileRead::recordAnswerFirst()
{
	if( fileAnswerEOF = true ) fileAnswerEOF = false;
	if( fileAnswerBOF = false ) fileAnswerBOF = true;
	(*RecordQuestions).RecordAnswers = (*RecordQuestions).listAnswers.begin();
}

/** Go to the Last Record */
void FileRead::recordAnswerLast()
{
	if( fileAnswerBOF = true ) 	fileAnswerBOF = false;
	if( fileAnswerEOF = false ) fileAnswerEOF = true;
	(*RecordQuestions).RecordAnswers = (*RecordQuestions).listAnswers.end();
	--(*RecordQuestions).RecordAnswers;
}

/** Record Next */
void FileRead::recordAnswerNext()
{
	++(*RecordQuestions).RecordAnswers;
	if( (*RecordQuestions).RecordAnswers == (*RecordQuestions).listAnswers.end() )
		{
		fileAnswerEOF = true;
		--(*RecordQuestions).RecordAnswers;
		}
		else
		{
		if( fileAnswerBOF = true ) fileAnswerBOF = false;
		}
}

/** Record previous */
void FileRead::recordAnswerPrevious()
{
	if( (*RecordQuestions).RecordAnswers == (*RecordQuestions).listAnswers.begin() )
		{
		fileBOF = true;
		}
		else
		{
		if( fileAnswerEOF = true ) fileAnswerEOF = false;
		--(*RecordQuestions).RecordAnswers;
		}
}

/** Get the value of the field question */
QString FileRead::getQuestion( int Field )
{
// QF_text, QF_picture, QF_type, QF_time, QF_tip, QF_explain
	switch( Field )
	{
		case QF_text:
			return (*RecordQuestions).Text;
			break;
		case QF_picture:
			return getPictureLocal( (*RecordQuestions).Picture );
			break;
		case QF_points:
			return QString().setNum( (*RecordQuestions).Points );
			break;
		case QF_time:
			return QString().setNum( (*RecordQuestions).Time );
			break;
		case QF_tip:
			return (*RecordQuestions).Tip;
			break;
		case QF_explain:
			return (*RecordQuestions).Explain;
			break;
	}
	return "";
}

/** Get the value of the field questions in integer */
int FileRead::getQuestionInt( int Field )
{
	switch( Field )
	{
		case QF_type:
			return (*RecordQuestions).Type;
			break;
		case QF_time:
			return (*RecordQuestions).Time;
			break;
		case QF_points:
			return (*RecordQuestions).Points;
			break;
	}
	return 0;
}

/** Get Answer field */
QString FileRead::getAnswer( int Field )
{
	// AField { AF_text, AF_value, AF_picture, AF_point };
	switch( Field )
	{
		case AF_text:
			return (*(*RecordQuestions).RecordAnswers).Text;
			break;
//		case AF_value:
//			(*(*RecordQuestions).RecordAnswers).Value ? return i18n("True") : return i18n("False");
//			break;
		case AF_point:
			return QString().setNum( (*(*RecordQuestions).RecordAnswers).Points );
			break;
	}	
	return "";
}

/** Get Answer field */
bool FileRead::getAnswerValue()
{
	return (*(*RecordQuestions).RecordAnswers).Value;
}

/** Get answer field */
int FileRead::getAnswerPoints()
{
	return (*(*RecordQuestions).RecordAnswers).Points;
}

/** Returns if this record is a end of file */
bool FileRead::recordEOF()
{
	return fileEOF;
}

/** Returns if this record is a begin of file */
bool FileRead::recordBOF()
{
	return fileBOF;
}

/** Returns if this record is a end of file */
bool FileRead::recordAnswerEOF()
{
	return fileAnswerEOF;
}

/** Returns if this record is a begin of file */
bool FileRead::recordAnswerBOF()
{
	return fileAnswerBOF;
}

/** Get an existing file */
QString FileRead::getPictureLocal( const QString &file )
{
if( file.isEmpty() ) return "";

QString picture = file;

if( !QFileInfo(picture).exists() )
	{
	picture = currentURL.directory(false,true) + QFileInfo(picture).fileName();
	if( !QFileInfo(picture).exists() ) { 	picture = ""; }
	}
	return picture;

}

/** Clear answers */
void FileRead::clearAnswers()
{
	 ((*RecordQuestions).listAnswers).clear();
}

/** Delete current record */
void FileRead::recordDelete()
{
	listQuestions.remove( RecordQuestions );
}

/** Swap two variables */
void FileRead::recordSwap( bool moveup )
{
	Questions listTMP;
	Questions listNEW;

	listTMP = (*RecordQuestions);

	if( moveup )
		{
		recordPrevious();
		listNEW = (*RecordQuestions);
		(*RecordQuestions) = listTMP;
		recordNext();
		(*RecordQuestions) = listNEW;
  	}
		else
		{
		recordNext();
		listNEW = (*RecordQuestions);
		(*RecordQuestions) = listTMP;
		recordPrevious();
		(*RecordQuestions) = listNEW;
		}
}

/** Save file */
bool FileRead::saveFile( const KURL &url, bool copyimages )
{
	KLocale *locale = KGlobal::locale();
	QDomDocument doc("document.xml");
	QTextStream stream;
	QFile QFilename;
	QString line;
	QStringList copyJOB;

	stream.setDevice(&QFilename);

	if( !url.url().isEmpty()	) currentURL = url;

	QFilename.setName( currentURL.directory(false,true)+currentURL.fileName() );

	if(!QFilename.open(IO_WriteOnly))
		{
		// No puede abrir la base
		return false;
		}

#if QT_VERSION < 300
	QString head( "<?xml version='1.0' encoding='"+ locale->charset() +"' standalone='yes' ?><!DOCTYPE educa>" );
#else
	QString head( "<?xml version='1.0' encoding='"+ QString::fromLatin1(locale->encoding()) +"' standalone='yes' ?><!DOCTYPE educa>" );
#endif
	doc.setContent( head );

	QDomElement Root = doc.createElement("Document");
	doc.appendChild( Root );

	QDomElement NodeInfo = doc.createElement("Info");
	Root.appendChild( NodeInfo );

	insertXML( doc, NodeInfo, "title", Header["title"] );
	insertXML( doc, NodeInfo, "category", Header["category"] );
	insertXML( doc, NodeInfo, "type", Header["type"] );
	insertXML( doc, NodeInfo, "level", Header["level"] );
	insertXML( doc, NodeInfo, "language", Header["language"] );

  if( !(Header["image"]).isEmpty() )
		{
		QDomElement Nodedefault = doc.createElement("default");
		if( copyimages )
			{
			copyJOB.append( Header["image"] );		
			Nodedefault.setAttribute( "image", QFileInfo(Header["image"]).fileName() );
			} else {
			Nodedefault.setAttribute( "image", Header["image"]);
			}
		NodeInfo.appendChild( Nodedefault );
		}

	if( !Header["name"].isEmpty() || !Header["email"].isEmpty() || !Header["www"].isEmpty() )
		{
		QDomElement Nodeauthor = doc.createElement("author");
		NodeInfo.appendChild( Nodeauthor );
		if( !Header["name"].isEmpty() ) 	insertXML( doc, Nodeauthor, "name", Header["name"] );
		if( !Header["email"].isEmpty() )	insertXML( doc, Nodeauthor, "email", Header["email"] );
		if( !Header["www"].isEmpty() )		insertXML( doc, Nodeauthor, "www", Header["www"] );
	  }

	QDomElement NodeData = doc.createElement("Data");
	Root.appendChild( NodeData );

	recordFirst();
  while ( !recordEOF() )
		{
		QDomElement question = doc.createElement("question");
		if( !getQuestion( QF_picture ).isEmpty() )
			{
			if( copyimages )
				{
				copyJOB.append( getQuestion( QF_picture ) );		
				question.setAttribute("image", QFileInfo( getQuestion( QF_picture ) ).fileName() );
				} else {
				question.setAttribute("image",  getQuestion( QF_picture ) );
				}
			}
		question.setAttribute( "type", getQuestionInt( QF_type ) );
		if( getQuestionInt( QF_points ) > 0 ) question.setAttribute( "points", getQuestion( QF_points ) );
		if( getQuestionInt( QF_time ) > 0 ) question.setAttribute( "time", getQuestion( QF_time ) );
		insertXML( doc, question, "text", getQuestion( QF_text ) );

		recordAnswerFirst();
		while( !recordAnswerEOF() )
		{
			if( getAnswerValue() )
				{
				QDomElement domELEMENT = doc.createElement( "true" );
				if( getAnswerPoints() > 0 ) domELEMENT.setAttribute("points", getAnswerPoints() );
				QDomText DATAelement = doc.createTextNode( getAnswer( AF_text ) );
				question.appendChild( domELEMENT );
				domELEMENT.appendChild( DATAelement );
				}	else {
//				insertXML( doc, question, "false", getAnswer( AF_text ) );
				QDomElement domELEMENT = doc.createElement( "false" );
				if( getAnswerPoints() > 0 ) domELEMENT.setAttribute("points", getAnswerPoints() );
				QDomText DATAelement = doc.createTextNode( getAnswer( AF_text ) );
				question.appendChild( domELEMENT );
				domELEMENT.appendChild( DATAelement );
				}
			recordAnswerNext();
		};

		if( !getQuestion( QF_tip ).isEmpty() ) insertXML( doc, question, "tip", getQuestion( QF_tip ) );
		if( !getQuestion( QF_explain ).isEmpty() ) insertXML( doc, question, "explain", getQuestion( QF_explain ) );

		NodeData.appendChild( question );
		recordNext();
		}

  doc.save( stream, 4);
  QFilename.close();

	if( copyimages == true && copyJOB.count() > 0 )
	{
  KURL::List	KurlLIST( copyJOB );
	KIO::CopyJob *copyjob;

	copyjob = KIO::copy( KurlLIST, currentURL.directory(false,true), true);
	}
	return true;

}

/** Insert xml format data */
void FileRead::insertXML( QDomDocument &doc, QDomElement &parent, const QString &tagName, const QString &data)
{
	QDomElement domELEMENT = doc.createElement( tagName );
	QDomText DATAelement = doc.createTextNode( data );

	parent.appendChild( domELEMENT );
	domELEMENT.appendChild( DATAelement );
}

/** Insert xml data format */
void FileRead::insertXML( QDomDocument &doc, QDomElement &parent, const QString &data)
{
	QDomText DATAelement = doc.createTextNode( data );
	parent.appendChild( DATAelement );
}

/** Get real picture */
QString FileRead::getPicture()
{
	if( getQuestion( QF_picture).isEmpty() && Header["image"].isEmpty() )
		{
		return locate("data", "keduca/pics/default.png" );
		} else if ( getQuestion( QF_picture ).isEmpty() )
			{
			return getPictureLocal( Header["image"] );
			} else {
			return getPictureLocal( getQuestion( QF_picture ) ) ;
			}
}

/** Get Header */
QString FileRead::getHeader(const QString &head)
{
	return Header[head];
}

/** Set header data */
void FileRead::setHeader( const QString field, const QString value)
{
	if( (Header[field]).isEmpty() )
		Header.insert( field, value );
		else
		Header.replace( field, value );
}

/** is Multi Answer */
bool FileRead::isMultiAnswer()
{
	int numOKanswer = 0;

	recordAnswerFirst();
	while( !recordAnswerEOF() )
		{
    if( (*(*RecordQuestions).RecordAnswers).Value == true ) numOKanswer++;
		recordAnswerNext();
		}
	
	if( numOKanswer > 1 )
		{ return true; }
		else
		{ return false; }
}
