/*
Copyright (c) 2007 Matt Williams matt@milliams.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) version 3 or, at the discretion of KDE e.V. (which shall
act as a proxy as in section 14 of the GPLv3), 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, see <http://www.gnu.org/licenses/>.
*/

#include "keducabuilder.h"
#include "keducamainwidget.h"

#include "kqtiassessmenttest.h"
#include "kqtitestpart.h"
#include "kqtiassessmentsection.h"
#include "kqtiassessmentitemref.h"

#include <KStandardAction>
#include <KActionCollection>
#include <QTimer>
#include <QBuffer>
#include <QTextStream>
#include <KFileDialog>
#include <KSaveFile>
#include <KIO/NetAccess>
#include <kdebug.h>

KEducaBuilder::KEducaBuilder() : KXmlGuiWindow()/*, _nativeFormat("application/x-edu")*/
{
    mainWidget = new KEducaMainWidget(this);
    setCentralWidget(mainWidget);
    QTimer::singleShot(0, this, SLOT(initObject()));
}

KEducaBuilder::~KEducaBuilder()
{
    
}

void KEducaBuilder::initObject()
{
    assessmentTest = 0;
    
    setupActions();
    setupGUI();
}

void KEducaBuilder::newTest()
{
    assessmentTest = new KQtiAssessmentTest("assessmenttest", i18n("Test"));
    KQtiTestPart* testPart = new KQtiTestPart();
    KQtiAssessmentSection* assessmentSection = new KQtiAssessmentSection("assessmentsection", i18n("Assessment Section"));
    testPart->addAssessmentSection(assessmentSection);
    assessmentTest->addTestPart(testPart);
    mainWidget->setAssessmentTest(assessmentTest);
}

void KEducaBuilder::openTest()
{
    QString fileName = KFileDialog::getOpenFileName();
    
    QString tmpFile;
    if( KIO::NetAccess::download( fileName, tmpFile, this ) )
    {
        QFile file(tmpFile);
        if(!file.open(QIODevice::ReadOnly))
        {
            return;
        }
        QDomDocument doc;
        doc.setContent(&file);
        kDebug() << "Opening " << fileName << "( tmp =" << tmpFile << ")";
        
        if (assessmentTest)
        {
            delete assessmentTest;
        }
        assessmentTest = new KQtiAssessmentTest(doc);
        
        kDebug() << endl << assessmentTest->document().toString().toLatin1();

        KIO::NetAccess::removeTempFile(tmpFile);
        
        mUrl = fileName;
        mainWidget->setAssessmentTest(assessmentTest);
        file.close();
    }
    else
    {
        kDebug() << "FileRead::openFile(): download NOT successful: " << fileName << endl;
    }
}

void KEducaBuilder::saveTest()
{
    if(!mUrl.isEmpty())
    {
        saveAsTest(mUrl);
    }
    else
    {
        saveAsTest();
    }
}

void KEducaBuilder::saveAsTest()
{
    saveAsTest(KFileDialog::getSaveFileName());
}

void KEducaBuilder::saveAsTest(const QString &outputFileName)
{
    KSaveFile file(outputFileName);
    file.open();
    
    file.write(assessmentTest->document().toByteArray());
    file.finalize();
    file.close();
    
    //TODO add saving of assessment items specified via itemRefs.
    //Tread through the item model, looking for assessmentItemRefs, save the file with the filename given by the itemRef and the contents of the assessmentItem.
    mUrl = outputFileName;
    
    QMap<KQtiAssessmentItem*,KQtiAssessmentItemRef*> list = mainWidget->assessmentItemRefs();
    foreach(KQtiAssessmentItem* item, list.keys())
    {
        kDebug() << KUrl(url()).directory()+"/"+list.value(item)->href();
        KSaveFile itemFile(KUrl(url()).directory()+list.value(item)->href());
        itemFile.open();
        
        kDebug() << endl << item->document().toByteArray();
        
        //itemFile.write(item->document().toByteArray());
        itemFile.finalize();
        itemFile.close();
    }
}

void KEducaBuilder::setupActions()
{
    KStandardAction::openNew(this, SLOT(newTest()), actionCollection());
    KStandardAction::open(this, SLOT(openTest()), actionCollection());
    KStandardAction::save(this, SLOT(saveTest()), actionCollection());
    KStandardAction::saveAs(this, SLOT(saveAsTest()), actionCollection());
    KStandardAction::quit(this, SLOT(close()), actionCollection());
    
    //KStandardAction::preferences(this, SLOT(optionsPreferences()), actionCollection());
    
    setupGUI();
}

#include "keducabuilder.moc"
