#include "quizsettings.h"

#define MINTIME              5
#define MAXTIME             99
#define DEFAULTTIME         25

#define MINQUESTION          1
#define MAXQUESTION         30

QuizSettings::QuizSettings( Controller *controller, QWidget *parent ) : QWidget( parent )
{
  setupUi( this );

  this->controller = controller;
  sfQuestionNumber->setSlider( MINQUESTION, MAXQUESTION, this->controller->getNumberOfQuestions() );
  if( this->controller->getTimePerQuestion() == 0 )
  {
    cbTime->setCheckState( Qt::Unchecked );
    sfTimePerQuestion->hide();
  }
  else
  {
    cbTime->setCheckState( Qt::Checked );
    sfTimePerQuestion->setSlider( MINTIME, MAXTIME, this->controller->getTimePerQuestion() );
  }

  //Categories
  QList< QString > categoryName;
  QList< int > categoryIds = this->controller->getAllCategoryIds();
  for( int i = 0; i < categoryIds.length(); i++)
    categoryName << this->controller->getCategoryNameAt( categoryIds[ i ] );
  categorySelection->setValues( categoryIds, categoryName, this->controller->getCurrentCategoryIds() );

  connect( cbTime, SIGNAL( stateChanged( int ) ), this, SLOT( timeStateSlot( int ) ) );
  connect( pbMenu, SIGNAL( clicked() ), this->controller, SLOT( showMenu() ) );
  connect( pbStart, SIGNAL( clicked( bool ) ), this, SLOT( startQuiz() ) );
}

QuizSettings::~QuizSettings( void )
{
}

void QuizSettings::timeStateSlot( int timeState )
{
  if( timeState == Qt::Checked )
  {
    sfTimePerQuestion->setSlider( MINTIME, MAXTIME, DEFAULTTIME );
    sfTimePerQuestion->show();
  }
  else
    sfTimePerQuestion->hide();
}

void QuizSettings::saveQuizSettings( void )
{
  QList< int > checkedCategoryIds = categorySelection->getCheckedIds();
  controller->saveQuizSettings( sfQuestionNumber->sliderValue(),
                                cbTime->isChecked() ? sfTimePerQuestion->sliderValue() : 0,
                                checkedCategoryIds );
}

void QuizSettings::startQuiz( void )
{
  if( categorySelection->getCheckedIds().length() <= 0 )
  {
    QPalette palette;
    palette.setColor( QPalette::WindowText, Qt::red );
    tlCategories->setPalette( palette );
    return;
  }

  saveQuizSettings();
  controller->showQuiz();
}
