/***************************************************************************
 *   Copyright (C) 2004 by Kraschinski Arnold                              *
 *   arnold.kra67@gmx.de                                                   *
 *                                                                         *
 *   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.,                                       *
 *   51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA.           *
 ***************************************************************************/
#include "verbviewtrainer.h"

// Qt header files
#include <QWidget>
#include <QLayout>
#include <QFile>
#include <QTextStream>
#include <QVector>

// KDE header files
#include <khtml_part.h>
#include <khtmlview.h>
#include <kurl.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <klineedit.h>

// Project header files
#include "verbdata.h"
#include "kverbossettings.h"


const int VerbViewTrainer::function[64] =  {0, 1, 2, 3, 4, 5, 18, 19, 20, 21, 22, 23, 6, 7, 8, 9, 10,
                                            11, 12, 13, 14, 15, 16, 17, 24, 25, 26, 27, 28, 29, 30,
                                            31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
                                            45, 46, 47, 48, 49, 50, 51, 52, 53, 55, 56, 57, 58, 59,
                                            54, 60, 61, 62, 63 };
const QString VerbViewTrainer::EMPTY = i18n("<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd""><html><head></head><body><p></p></body></html>");

const QString VerbViewTrainer::HINT_MESSAGE = i18n("<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd""><html><head></head><body><p style=""text-align:center;"">Enter the infinitive of a Spanish verb and then press ENTER.</p></body></html>");

const QString VerbViewTrainer::UNKNOWN_MESSAGE = i18n("<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd""> <html> <head> <title></title> <meta http-equiv=""Content-Type"" content=""text/html; charset=ISO-8859-15""> <style type=""text/css""> .heavy { font-family:arial; font-weight:800; font-size: 25pt; color:#006699 } </style> </head> <body> <table width=""100%""> <tbody> <tr> <td width=""5%"">  </td> <td width=""*"" height=""500"" style=""vertical-align:middle; text-align:center;""> <p class=""heavy"">Lo siento! No conozco el verbo:<br><span style=""color:red;"">**infinitivo**</span></p> </td> <td width=""5%"">  </td> </tr> </tbody> </table> </body> </html>");

VerbViewTrainer::VerbViewTrainer(QWidget *parent )
: Trainer(parent), m_clear(true), m_oldVerb("")
{
    QGridLayout* qVerbViewLayout = new QGridLayout( this );
    qVerbViewLayout->setContentsMargins( 0, 0, 0, 0 );
    
    m_htmlRenderer = new KHTMLPart(this);
    qVerbViewLayout->addWidget(m_htmlRenderer->view(), 0, 0);
    
    m_lineEdit = new KLineEdit(this);
    qVerbViewLayout->addWidget(m_lineEdit, 1, 0);
    connect(m_lineEdit, SIGNAL(textEdited(const QString&)), this, SLOT(slotVerbChanged()));
    connect(m_lineEdit, SIGNAL(returnPressed(const QString&)), this, SLOT(slotVerbEntered(const QString&)));
    m_htmlRenderer->begin();
    m_htmlRenderer->write( HINT_MESSAGE );
    m_htmlRenderer->end();
}

VerbViewTrainer::~VerbViewTrainer()
{
    delete m_htmlRenderer;
    m_htmlRenderer = 0;
}

void VerbViewTrainer::next()
{
    slotVerbEntered( m_lineEdit->text() );
}

void VerbViewTrainer::slotVerbChanged()
{
    if (m_clear) {
        m_htmlRenderer->begin();
        m_htmlRenderer->write( EMPTY );
        m_htmlRenderer->end();
        m_lineEdit->setText(m_lineEdit->text().right(1));
        m_clear = false;
    }
}

void VerbViewTrainer::slotVerbEntered(const QString &s)
{
    if (s.isEmpty() || (s == m_oldVerb)) {
        m_htmlRenderer->begin();
        m_htmlRenderer->write( HINT_MESSAGE );
        m_htmlRenderer->end();
        m_clear = true;
    } else {
        Verb* v = Verbdata::find( s );
        if ( v == 0 ) {
            m_htmlRenderer->begin();
            QString text = UNKNOWN_MESSAGE;
            m_htmlRenderer->write( text.replace( "**infinitivo**", s ) );
            m_htmlRenderer->end();
            m_clear = true;
            emit someExerciseSolved(1, 0);
        } else {
            QVector<QString> forms = v->conjugate( true );

            m_htmlRenderer->begin();
            QString filename("");
            if ( v->reflexive() ) {
                filename = KStandardDirs::locate("appdata", "data/verbtabellese.html");
            } else {
                filename = KStandardDirs::locate("appdata", "data/verbtabelle.html");
            }

            if ( ( KVerbosSettings::autoSelect() ) && ( !v->selected() ) ) {
                v->setSelected( true );
                QStringList s = KVerbosSettings::verbselection();
                s << ( v->infinitive() + "=" + QString::number(v->level()) + "=" + QString::number(v->lastDay()) );
                KVerbosSettings::setVerbselection( s );
                KVerbosSettings::self()->writeConfig();
            }

            QFile source(filename);
            if (!source.open(QIODevice::ReadOnly)) {
                kDebug() << "The template for the QVerbViewTrainer output is missing. Check $KDEIR/share/apps/kverbos/data" << endl;
            } else {
                QTextStream in(&source);
                int formcount(0);
                while (!in.atEnd()) {
                    // Read the file line by line and fill the gaps with the forms of the verb
                    int pos1(0);
                    int pos2;
                    QString line = in.readLine();
                    while (line.indexOf("**", pos1) >= 0) {
                        pos1 = line.indexOf("**", pos1);
                        pos2 = line.indexOf("**", pos1 + 2);
                        if ((pos1 == -1) || (pos2 == -1)) {
                            kDebug() << "There is a gap missing in the verbtabelle.html or verbtabellese.html file for the qverbviewtrainer.cpp." << endl;
                        } else {
                            // because of the stars it is necessary to add 2
                            QString form = line.mid(pos1, pos2 - pos1 + 2);
                            // now replace the gab with the right form
                            if (form == "**form**") {
                                form = forms[function[formcount]];
                                formcount++;
                            } else if (form == "**participio**") {
                                form = forms[function[61]];
                            } else if (form == "**infinitivo**") {
                                form = s;
                            } else if (form == "**gerundio**") {
                                form = forms[function[60]];
                            }
                            line.replace(pos1, pos2 - pos1 + 2, form);
                        }
                        pos1 = pos2 + 2;
                    }
                    m_htmlRenderer->write(line);
                }
                source.close();
                m_htmlRenderer->end();
                m_oldVerb = s;
            }
            m_clear = true;
            Verbdata::reportTraining( v, true, false );
            emit someExerciseSolved(1, 1);
        }
    }
}

void VerbViewTrainer::slotChar(QString ch)
{
    if (m_lineEdit->hasFocus()) {
        m_lineEdit->insert(ch);
    }
}


#include "verbviewtrainer.moc"
