#include "deletequestion.h"

DeleteQuestion::DeleteQuestion( Controller *controller, QWidget *parent ) : QWidget( parent )
{
  setupUi( this );
  this->controller = controller;

  QVBoxLayout *vLayout = new QVBoxLayout( gbMain );
  vLayout->setMargin( 0 );

  QList< QGroupBox* > gbCategoryQuestions;
  QList< int > categoryIds = this->controller->getAllCategoryIds();
  for( int i = 0; i < categoryIds.length(); i++ )
  {
    //GroupBox
    gbCategoryQuestions << new QGroupBox( this->controller->getCategoryNameAt( categoryIds[ i ] ) );
    QVBoxLayout *gbLayout = new QVBoxLayout();
    gbLayout->setMargin( 0 );
    gbCategoryQuestions[ i ]->setLayout( gbLayout );
    vLayout->addWidget( gbCategoryQuestions[ i ] );

    //QuestionSelection / CheckBoxSelection
    questionSelections << new CheckBoxSelection();
    QList< int > categoryId;
    categoryId << categoryIds[ i ];
    QList< int > questionIds = this->controller->getQuestionIdsToCategoryIds( categoryId );
    QList< QString > questionTexts;
    for( int i = 0; i < questionIds.length(); i++ )
      questionTexts << this->controller->getQuestionTextAt( questionIds[ i ] );
    QList< int > emptyIntList;
    questionSelections[ i ]->setValues( questionIds, questionTexts, emptyIntList );
    gbCategoryQuestions[ i ]->layout()->addWidget( questionSelections[ i ] );
  }
  mainScrollAreaWidget->setLayout( static_cast< QVBoxLayout* >( gbMain->layout() ) );
  layout()->removeWidget( gbMain );
  delete gbMain;

  for( int i = 0; i < questionSelections.length(); i++)
    connect( questionSelections[ i ], SIGNAL( somethingChanged( QList< int > ) ), this, SLOT( selectedQuestionsChanged() ) );
  connect( pbManageQuestionsMenu, SIGNAL( clicked( bool ) ), this->controller, SLOT( showManageQuestionsMenu() ) );
  connect( pbDelete, SIGNAL( clicked( bool ) ), this, SLOT( deleteSlot() ) );
}

void DeleteQuestion::deleteSlot( void )
{
  QList< int > questionIds;
  for( int i = 0; i < questionSelections.length(); i++ )
    for( int j = 0; j < questionSelections[ i ]->getCheckedIds().length(); j++ )
      questionIds << questionSelections[ i ]->getCheckedIds()[ j ];

  for( int i = 0; i < questionIds.length(); i++ )
    controller->deleteQuestionAndAnswers( questionIds[ i ] );

  controller->showDeleteQuestion();
}

void DeleteQuestion::selectedQuestionsChanged( void )
{
  int numberOfQuestionIds = 0;
  for( int i = 0; i < questionSelections.length(); i++ )
    numberOfQuestionIds += questionSelections[ i ]->getCheckedIds().length();
  tlSelectedQuestions->setText( QString::number( numberOfQuestionIds ) );
}
