#include "TriviaApp.h"
#include <QDomDocument>
#include <QFile>
#include <QMessageBox>
#include <iostream>
#include <QLabel>
#include <QApplication>
#include <QVBoxLayout>
#include <QInputDialog>
#include <QDir>
#include <QTime>
#include <QAction>
#include <QMenuBar>
#include <QDialog>
#include <QStatusBar>
#include <QPushButton>

#include "Nickname.h"
#include "Question.h"
#include "SingleChoiceQuestion.h"
#include "NumericQuestion.h"
#include "TextualQuestion.h"
#include "MainWindow.h"

using namespace std;

TriviaApp::TriviaApp(int argc, char* argv[]) :
    QApplication (argc, argv){
    userScore = 0;
    bottonContinue = new QPushButton("Continue");
}

TriviaApp::~TriviaApp(){
    qDeleteAll(questions);
}

int TriviaApp::crear(){

    Nickname *nick = new Nickname();
    nick->run();
    mainwindow.show();
    if ( ! loadQuestions() ) return 1;
        printQuestions();
    return this->exec();
}

inline bool showError(const QString& message){
    QMessageBox::critical(0, "Error", message);
    return false;
}

bool TriviaApp::loadQuestions(){
    QFile file(triviaFilename);
    if ( ! file.open(QIODevice::ReadOnly | QIODevice::Text) )
        return showError( QString("Could not open %1").arg(triviaFilename) );
    QDomDocument document("trivia");
    QString errorMsg;
    int errorLine = 0;
    int errorColumn = 0;
    if ( ! document.setContent(&file, &errorMsg, &errorLine, &errorColumn) )   {
        file.close();
        return showError(QString("%1:%2.%3: %4").arg(triviaFilename).arg(errorLine).arg(errorColumn).arg(errorMsg));
    }
    file.close();
    QDomElement triviaElement = document.documentElement();
    for( QDomNode node = triviaElement.firstChild(); ! node.isNull(); node = node.nextSibling() )   {
        QDomElement element = node.toElement(); // try to convert the node to an element.
        if( element.isNull() || element.tagName() != "question" ) continue;
        Question* question = createQuestion(element.attribute("type"), element.attribute("duration"));
        if ( ! question->loadFromNode(element) )      {
            // Hubo una pregunta mala. Que hacer con ella?
            delete question;
            continue;
        }
        questions.append(question);
    }
    return true;
}

void TriviaApp::printQuestions() {
    connect(bottonContinue, SIGNAL(pressed()), this , SLOT(loadWidget()));
    bottonContinue->show();

}

Question* TriviaApp::createQuestion(const QString& type, const QString& duration){
    if ( type == "single_choice" ) return new SingleChoiceQuestion(duration, bottonContinue);
    if ( type == "numeric" ) return new NumericQuestion(duration, bottonContinue);
    if ( type == "textual" ) return new TextualQuestion(duration, bottonContinue);
    return new Question();
}

void TriviaApp::loadWidget(){
    if (!questions.isEmpty()) {
        QTime time = QTime::currentTime();
        qsrand((uint)time.msec());
        int randomValue = 0;
        randomValue = qrand() % (questions.count());
        questions[randomValue]->aplicar(userScore);
        mainwindow.setCentralWidget(questions[randomValue]);
        questions.remove(randomValue);
    }
}
