#include <QtGui>
#include "window.h"
#include "informationdialog.h"
#include <QGridLayout>
#include <QPushButton>
#include <QGroupBox>
#include <QDialogButtonBox>
#include <QRadioButton>
#include <QLineEdit>
#include <QComboBox>
#include "connectdialog.h"
#include "Server.h"
#include "Client.h"
#include <time.h>


Window::Window(QWidget *parent)
    : QWidget(parent)
    ,isFirst(true)
    , arraySize(0)
    , host(0)
    , multiplayer(0)
{
   trivia = new TriviaApp(this);


    mainLayout = new QGridLayout;

    createIntroGroupPage();
    connect(this, SIGNAL(multiplayerSignal()), this, SLOT(multiplayerSelected()));
    connect(this, SIGNAL(selectQuestion(int)), this, SLOT(showQuestion(int)));

}

void Window::createConnectDialog()
{
   connectDialog = new ConnectDialog(this);
}


void Window::multiplayerSelected()
{
   createConnectDialog();
   connect(connectDialog, SIGNAL(joinServerSignal()), this, SLOT(joinServer()));
   connect(connectDialog, SIGNAL(createNewGame()), this, SLOT(createServer()));
}

void Window::createIntroGroupPage()
{
    introGroupPage = new QGroupBox();

    QLabel *nameLabel = new QLabel(tr("Nickname:"));
    QLineEdit *nameLineEdit = new QLineEdit;
    nameLineEdit->setFocus();

    QLabel *modeLabel = new QLabel(tr("Mode:"));
    QComboBox *modeComboBox= new QComboBox;

    modeComboBox->addItem(tr("Singleplayer"));
    modeComboBox->addItem(tr("Multiplayer"));

    connect(nameLineEdit, SIGNAL(textChanged( const QString &)), trivia, SLOT(getName( const QString &)));//////////////////////
    //connect(modeComboBox, SIGNAL(activated(int)), trivia, SLOT(decideMode(int)));
    connect(modeComboBox, SIGNAL(activated(int)), this, SLOT(decideMode(int)));

    QGridLayout *layout = new QGridLayout;
    layout->addWidget(nameLabel, 0,0,4,4);
    layout->addWidget(nameLineEdit,0,2,4,4);
    layout->addWidget(modeLabel,1,0,4,4);
    layout->addWidget(modeComboBox,1,2,4,4);

    introGroupPage->setLayout(layout);

    mainLayout->addWidget(introGroupPage);

    continueButton = new QPushButton(tr("Start"));
    //connect(continueButton, SIGNAL(clicked()), this, SLOT(showQuestion()));
    connect(continueButton, SIGNAL(clicked()), this, SLOT(startPressed()));

    mainLayout->addWidget(continueButton,1,0,Qt::AlignRight);

    setLayout(mainLayout);

    setWindowTitle(tr("Trivia"));
    resize(450, 250);
}

void Window::decideMode(int i)
{
   if(i == 1)
   {
      multiplayer = true;
      return;
   }
   multiplayer = false;
}

void Window::startPressed()
{
   if(!multiplayer)
   {
      qDebug() << qPrintable("singleSelected");
      emit singlePlayerSignal();
      return;
   }
   qDebug() << qPrintable("multiSelected");
   emit multiplayerSignal();
}

void Window::createQuestAnswGroup()
{

    QVBoxLayout *vbox = new QVBoxLayout;
    QLabel *label = new QLabel(pregunta);
    vbox->addWidget(label);

    questAnswGroup = new QGroupBox();

    if(trivia->actQuestion->type=="single_choice")
    {
        createSingleChoiceOptions();
        vbox->addWidget(singleChoiceOptions);

    } else
    {
        createAnswerLineGroup();
         vbox->addWidget(answerLine);
    }

    vbox->addStretch(2);
    questAnswGroup->setLayout(vbox);

}


void Window::showQuestion(int index)
{
    pregunta = trivia->getNewQuestion(index);
    resize(700, 400);
    ++trivia->questionsCounter;

    trivia->userAnswer = "";
    if(isFirst)
    {
        delete introGroupPage;
        delete continueButton;
        createButtonBox();
        mainLayout->addWidget(buttonBox, 3, 3, Qt::AlignBottom);
        isFirst = false;
    }else
    {
        delete questAnswGroup;
        delete resultLabel;
        delete timeScoreBox;
        continueButton->setDisabled(true);
        checkButton->setDisabled(false);

    }

    createQuestAnswGroup();
    createTimeScoreBox();
    mainLayout->addWidget(questAnswGroup, 0, 0, 3, 3);
    mainLayout->addWidget(timeScoreBox, 0, 3, 3, 3);

}



void Window::createButtonBox()
{
    buttonBox = new QDialogButtonBox;

    continueButton = buttonBox->addButton("Next", QDialogButtonBox::ActionRole);
    checkButton = buttonBox->addButton("Check", QDialogButtonBox::ActionRole);
    closeButton = buttonBox->addButton("Finish", QDialogButtonBox::ActionRole);
    continueButton->setDisabled(true);

    connect(closeButton, SIGNAL(clicked()), this, SLOT(showStadistics()));
    connect(checkButton, SIGNAL(clicked()), this, SLOT(checkAnswers()));
    connect(continueButton, SIGNAL(clicked()), this, SLOT(getQuestion()));

}

void Window::createTimeScoreBox()
{
    timeScoreBox = new QGroupBox;
    timeScoreBox->setFlat(true);

    QLabel *label = new QLabel("Your Score:");
    QLCDNumber *lcdScore = new QLCDNumber();
    lcdScore->setFixedSize(50,30);
    lcdScore->display(trivia->getScore());
    lcdScore->setStyleSheet(" background-color:rgb(0,100,0)");

    time = new Countdown (0,5);
    connect(time, SIGNAL(stopped()), this, SLOT(checkAnswers()));
    connect(checkButton, SIGNAL(clicked()), time, SLOT(stopClock()));

    QVBoxLayout *vbox = new QVBoxLayout;
    vbox->addWidget(time, 0,Qt::AlignRight);
    vbox->addWidget(label, 1,Qt::AlignRight);
    vbox->addWidget(lcdScore,0,Qt::AlignRight);
    vbox->addStretch(2);
    timeScoreBox->setLayout(vbox);

}







void Window::checkAnswers()
{
    if(checkButton->isEnabled())
    {
        if(trivia->actQuestion->getType()=="single_choice")
        {
            getSelectedOption(); ////////////////////
        }
        continueButton->setDisabled(false);
        checkButton->setDisabled(true);

        if(trivia->isCorrect())
    {
        resultLabel = new QLabel("Congratulations! Correct answer");
        ++trivia->correctCounter;
        //QSound sound("good.wav");
        //sound.play();


    } else
    {
        resultLabel = new QLabel("This is the correct answer");
        if(trivia->actQuestion->getType()!="single_choice"){
            answerLine->setText(trivia->actQuestion->getAnswer());

            answerLine->setStyleSheet("color:rgb(0,80,0);background-color:rgb(220,255,220)");
            answerLine->setReadOnly(true);

        }
    }
    resultLabel->setStyleSheet("color:rgb(250,120,0)");
    mainLayout->addWidget(resultLabel, 2, 1, Qt::AlignCenter);
    }
}


void Window::getSelectedOption()
{
    for(size_t i = 0 ; i<arraySize ; ++i)
    {
        if(singleChoiceOptions->buttons()[i]->isChecked())
        {

            trivia->userAnswer = QString::number(i+1);
            if(!trivia->isCorrect())
            {
                singleChoiceOptions->buttons()[i]->setStyleSheet("background-color: red");
            }
        }
    }

    singleChoiceOptions->buttons()[trivia->actQuestion->getAnswer().toInt()-1]->setStyleSheet("background-color: green");
    singleChoiceOptions->buttons()[trivia->actQuestion->getAnswer().toInt()-1]->setChecked(true);
   // std::cout<<trivia->actQuestion->getAnswer().toStdString()<<std::endl;
}




void Window::createSingleChoiceOptions()
{
    QVector<QString> optns = *(trivia->actQuestion->getOptions());
    size_t cantidadOpciones = optns.size();
    //QRadioButton *botonesOpciones[cantidadOpciones];
    QVector<QRadioButton*> botonesOpciones;
    singleChoiceOptions = new QDialogButtonBox(Qt::Vertical);
    arraySize = 0;

    for (size_t i = 0; i < cantidadOpciones; ++i)
    {
        QString str = optns.at(i);
        //botonesOpciones[i] = new QRadioButton(str);
        botonesOpciones.push_back(new QRadioButton(str));
        botonesOpciones[i]->setCheckable(true);
        botonesOpciones[i]->setAutoExclusive(true);
        singleChoiceOptions->addButton(botonesOpciones[i], QDialogButtonBox::ActionRole);
        ++arraySize;

    }
}

void Window::createAnswerLineGroup()
{
    answerLine = new QLineEdit;
    answerLine->setFocus();
    connect(answerLine, SIGNAL(textChanged( const QString &)), trivia, SLOT(getAnswerLine( const QString &)));
}

void Window::showStadistics()
{
    if(continueButton->isEnabled())
    {
        delete resultLabel;
    }
    delete questAnswGroup;
    delete timeScoreBox;
    delete buttonBox;

    QLabel *usernameLabel = new QLabel(trivia->username);

    QLabel *answeredLabel = new QLabel("Questions answered: ");
    QLabel *answeredCount = new QLabel(QString::number(trivia->questionsCounter));

    QLabel *correctLabel = new QLabel("Correct answers: ");
    QLabel *correctCount = new QLabel(QString::number(trivia->correctCounter));

    QLabel *scoreLabel = new QLabel("Your score: ");
    QLabel *scoreCount = new QLabel(QString::number(trivia->score));

    mainLayout->addWidget(usernameLabel, 0, 1,Qt::AlignCenter);
    mainLayout->addWidget(answeredLabel, 0, 1, 4, 4);
    mainLayout->addWidget(answeredCount, 0, 3, 4, 4);
    mainLayout->addWidget(correctLabel, 1, 1, 4, 4);
    mainLayout->addWidget(correctCount, 1, 3, 4, 4);
    mainLayout->addWidget(scoreLabel,  2, 1, 4, 4);
    mainLayout->addWidget(scoreCount, 2, 3, 4, 4);
    mainLayout->rowStretch(1);

    closeButton = new QPushButton("Finish");
    mainLayout->addWidget(closeButton,3,4,3,4,Qt::AlignBottom);


    connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));

}

void Window::createServer()
{
   server = new Server(this);
   if ( ! server->listen(QHostAddress::Any, connectDialog->getPort().toUInt()) )
   {
      qDebug("Failed to bind to port %i\n", connectDialog->getPort().toUInt());
      return;
   }
   qDebug("Listening in port %i", connectDialog->getPort().toUInt());
   client = new Client(this);
   client->connectToHost(QHostAddress::LocalHost, connectDialog->getPort().toUInt());
   host = true;
   waitingUser(connectDialog->getPort().toUInt());
   connectDialog->hide();
   connect(this, SIGNAL(newUserSignal()), this, SLOT(newUser()));
   return;
}

void Window::joinServer()
{
   client = new Client(this);
   client->connectToHost(connectDialog->getAddress(), connectDialog->getPort().toUInt());
   qDebug() << qPrintable (connectDialog->getAddress());
   QString buffer = "User";
   qDebug() << qPrintable(trivia->getUsername());
   emit client->send(buffer.append(trivia->getUsername()));
   connectDialog->hide();
   //connect(client, SIGNAL(selectedQuestion(int)), this, SLOT(selectedQuestion(int)));
}

void Window::waitingUser(int port)
{
   informationDialog =  new InformationDialog(connectDialog);
   QString message = "Esperando Usuario en el puerto ";
   informationDialog->setText(message.append(QString::number(port)));
   informationDialog->show();
}

void Window::newUser()
{
   informationDialog->close();
}

void Window::getQuestion()
// DEPENDIENDO DEL MODO EMITIA UN NUMERO AL AZAR PARA
// LOGRAR SABER CUAL SERIA LA SIGUIENTE PREGUNTA.
{
   /*
   srand(0);
   if(!multiplayer)
   {
      //emit selectQuestion(rand() % questions.size());
      return;
   }
   if(host)
   {
      QString buffer = "Next Question\n";
      emit client->send(buffer.append(rand() % questions.size()));
      */

}
