/***************************************************************************
                          keducaview.cpp  -  description
                             -------------------
    begin                : Thu May 24 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 "keducaview.h"
#include "keducaview.moc"

#include <klocale.h>
#include <kstandarddirs.h>
#include <kconfig.h>
#include <kaction.h>
#include <kstdaction.h>

#include <qtimer.h>

KEducaView::KEducaView(QWidget *parent, const char *name ) : QWidget(parent,name),
                                                             _timeoutTimer(0L)
{
}

KEducaView::~KEducaView()
{
    delete _questionText;
    delete _buttonGroup;
    delete _split;
    delete _buttonNext;
    delete _viewResults;
    delete _keducaFile;
}

/** Init graphical interface */
void KEducaView::init()
{
    QVBoxLayout *vbox = new QVBoxLayout( this );
    vbox->setSpacing( 6 );
    vbox->setMargin( 11 );

    _vbox2 = new QVBoxLayout( vbox );
    _split = new QSplitter( this );
    _split->setOrientation( QSplitter::Vertical );
    _questionText = new KQuestion( _split, "kquestion" );
    _buttonGroup = new KGroupEduca( _split, "ButtonGroup" );
    _buttonGroup->setRadioButtonExclusive( TRUE );
    _vbox2->addWidget( _split );

    _viewResults = new QTextView(this);
    _viewResults->hide();
    vbox->addWidget( _viewResults );

    _buttonNext = new QPushButton( this, "ButtonNext" );
    _buttonNext->setText( i18n("&Next >>") );
    _buttonNext->setAutoRepeat( FALSE );
    _buttonNext->setToggleButton( FALSE );
    _buttonNext->setDefault( TRUE );
    connect( _buttonNext, SIGNAL( clicked() ), SLOT( slotButtonNext() ) );
    vbox->addWidget( _buttonNext );
}

/** Button Next action */
void KEducaView::slotButtonNext()
{
    // stop the timer
    if (_timeoutTimer)
    {
      _timeoutTimer->stop();
      _questionText->countdown(0);
    }

    if( _questionText->isVisible() )	setResults();
    _buttonGroup->clearAnswers();

    if( !_showResultFinish && _questionText->isVisible() )
    {
        showResults( _currentResults );
    }
    else
    {
        _keducaFile->recordNext();
        if( !showRecord() )
        {
            configWrite();
            _buttonNext->hide();
            showResults( _results );
        }
    }
}

/** Show record, returns false if there is no record to show. */
bool KEducaView::showRecord()
{
    if( _keducaFile->recordEOF() ) return false;

    if( _viewResults->isVisible() )
    {
        _viewResults->hide();
        _split->show();
    }

    _keducaFileIndex++;
    bool MultiAnswer = _keducaFile->isMultiAnswer();

    _questionText->setPixmap( _keducaFile->getPicture() );
    _questionText->setText( "<b>"
                            + i18n("Question %1").arg(_keducaFileIndex)
                            + " </b><hr/><table><tr><td>"
                            + _keducaFile->getQuestion( FileRead::QF_TEXT ) +
                            "</td></tr></table><" );

    if( MultiAnswer )
        _buttonGroup->setType( KGroupEduca::Check );
    else
        _buttonGroup->setType( KGroupEduca::Radio );

    _keducaFile->recordAnswerFirst();
    while( !_keducaFile->recordAnswerEOF() )
    {
        if( !_keducaFile->getAnswer(FileRead::AF_TEXT).isEmpty() )
            _buttonGroup->insertAnswer( _keducaFile->getAnswer(FileRead::AF_TEXT) );
        _keducaFile->recordAnswerNext();
    };

    // start the timer
    int timeout = _keducaFile->getQuestionInt(FileRead::QF_TIME);
    if (timeout > 0)
    {
      if (!_timeoutTimer)
      {
        _timeoutTimer = new QTimer(this);
        connect(_timeoutTimer, SIGNAL(timeout()),
                this, SLOT(questionTimedOut()));
      }
      _timeoutTimer->start(1000*timeout);
      _questionText->countdown(timeout);
      _questionText->countdownVisible(true);
    }else{
      _questionText->countdownVisible(false);
    }
    return true;
}

void KEducaView::questionTimedOut()
{
  slotButtonNext();
}

/** Show results */
void KEducaView::showResults(const QString &text)
{
    _split->hide();
    _viewResults->setText( text );
    _viewResults->show();
}

/** Set results */
void KEducaView::setResults()
{
    bool isCorrect = true;
    int nAnswer = 0;
    QString yourAnswer = "";
    QString correctAnswer = "";

    _keducaFile->recordAnswerFirst();
    while( !_keducaFile->recordAnswerEOF() )
    {
        QString answertext = _keducaFile->getAnswer( FileRead::AF_TEXT );
        if( !answertext.isEmpty() )
        {
            if(_buttonGroup->isChecked(nAnswer) != _keducaFile->getAnswerValue())
            {
                isCorrect=false;
                if(_buttonGroup->isChecked(nAnswer)) yourAnswer += "<LI><FONT COLOR=#b84747><B>" + answertext + "</B></FONT></LI>";
                if(_keducaFile->getAnswerValue()) correctAnswer += "<LI><FONT COLOR=#006b6b><B>" + answertext + "</B></FONT></LI>";
            }
            else
            {
                if(_buttonGroup->isChecked(nAnswer)) yourAnswer += "<LI><B>" + answertext + "</B></LI>";
                if(_keducaFile->getAnswerValue()) correctAnswer += "<LI><B>" + answertext + "</B></LI>";
            }
        }
        _keducaFile->recordAnswerNext();
        nAnswer++;
    }

    _currentResults = "<TABLE WIDTH=100% BORDER=0 CELLPADDING=0 CELLSPACING=0><COL WIDTH=244*><COL WIDTH=12*><THEAD><TR>";

    if( isCorrect)
    {
        _correctAnswer++;
        _currentResults += "<TH WIDTH=95% BGCOLOR=#006b6b>";
    } else {
        _incorrectAnswer++;
        _currentResults += "<TH WIDTH=95% BGCOLOR=#b84747>";
    }

    _currentResults += "<P ALIGN=LEFT><FONT COLOR=#ffffff SIZE=4> ";
    _currentResults += _keducaFile->getQuestion( FileRead::QF_TEXT );
    _currentResults += "</FONT></TH>";

    if( isCorrect )
        _currentResults += "<TH WIDTH=5% BGCOLOR=#006b6b SDVAL=1 SDNUM=1034;>";
    else
        _currentResults += "<TH WIDTH=5% BGCOLOR=#b84747 SDVAL=1 SDNUM=1034;>";

    _currentResults += "<P><FONT COLOR=#ffffff>";
    _currentResults += QString().setNum( _keducaFileIndex );
    _currentResults += "</FONT></TH>";
    _currentResults += "</TR></THEAD><TBODY>";

    _currentResults += "<TR><TD COLSPAN=2 WIDTH=100% BGCOLOR=#eeeeee ><P>";
    if( isCorrect )
        _currentResults += i18n( "The answer is:");
    else
        _currentResults += i18n( "The correct answer is:");
    _currentResults += "</TD></TR>";

    _currentResults += "<TR><TD COLSPAN=2 WIDTH=100% BGCOLOR=#eeeeee><UL>";
    _currentResults += correctAnswer;
    _currentResults += "</UL></TD></TR>";
    if( !isCorrect )
    {
        _currentResults += "<TR><TD COLSPAN=2 WIDTH=100% BGCOLOR=#eeeeee><P>";
        _currentResults += i18n( "Your answer was:");
        _currentResults += "</TD></TR>";
        _currentResults += "<TR><TD COLSPAN=2 WIDTH=100% BGCOLOR=#eeeeee><UL>";
        _currentResults += yourAnswer;
        _currentResults += "</UL></TD></TR>";
    }
    _currentResults += "	</TBODY></TABLE><P></P>";

    _results += _currentResults;
}
/** Open url */
bool KEducaView::openURL( const KURL &url)
{
    _keducaFile = new FileRead();
    if( !_keducaFile->openFile( url.url() ) ) return false;
    _keducaFile->recordFirst();
    _keducaFile->recordAnswerFirst();

    _correctAnswer = 0;
    _incorrectAnswer = 0;
    _keducaFileIndex = 0;
    _results = "";

    init();
    configRead();
    showRecord();

    return true;
}

/** Read settings */
void KEducaView::configRead()
{
    KConfig *config = KGlobal::config();

    config->setGroup( "keducaview" );
    _split->setSizes( config->readIntListEntry("Splitter_size") );

    config->setGroup("Options");
    _showResultFinish = config->readBoolEntry("ResultFinish", true );
}

/** Write settings */
void KEducaView::configWrite()
{
    KConfig *config = KGlobal::config();
    config->setGroup( "keducaview" );
    config->writeEntry("Splitter_size", _split->sizes() );
    config->sync();
}
