#include "managequestionsmenu.h"

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

  connect( pbAddQuestion, SIGNAL( clicked( bool ) ), controller, SLOT( showAddQuestion() ) );
  connect( pbAddQuestionsPerFile, SIGNAL( clicked( bool ) ), controller, SLOT( showAddQuestionsPerFile() ) );
  connect( pbExportQuestions, SIGNAL( clicked( bool ) ), this, SLOT( openExportFileDialog() ) );
  connect( pbDeleteQuestion, SIGNAL( clicked( bool ) ), controller, SLOT( showDeleteQuestion() ) );
  connect( pbDatabaseEditor, SIGNAL( clicked( bool ) ), controller, SLOT( showDatabaseEditor() ) );

  connect( pbMenu, SIGNAL( clicked() ), controller, SLOT( showMenu() ) );
}

void ManageQuestionsMenu::exportQuestions( void )
{
  QString fileText( "" );
  QList< int > questionIds = controller->getAllQuestionIds();
  for( int i = 0; i < questionIds.length(); i++ )
  {
  //Category
    QList< QString > categoryNames = controller->getCategoryNamesAt( controller->getCategoryIdForQuestionId( questionIds[ i ] ) );
    fileText += makeLine( categoryNames ) + "\r\n";
  //Question
    QList< QString > questionTexts = controller->getQuestionTextsAt( questionIds[ i ] );
    fileText += makeLine( questionTexts ) + "\r\n";
  //Answers + Explanations
    QList< int > answerIds = controller->getTrueAnswerIdsToQuestionId( questionIds[ i ] );
    answerIds += controller->getFalseAnswerIdsToQuestionId( questionIds[ i ] );
    for( int j = 0; j < answerIds.length(); j++ )
    {
      QString answerExplanationTexts1;
      QList< QString > answerTexts1 = controller->getAnswerTextsAt( answerIds[ j ] );;
      QList< QString > explanationTexts1 = controller->getExplanationTextsToAnswerId( answerIds[ j ] );
      QString semicolon = explanationTexts1.isEmpty() ? "" : ";";
      answerExplanationTexts1 += makeLine( answerTexts1 ) + semicolon;
      answerExplanationTexts1 += ( makeLine( explanationTexts1 ) + "\r\n" );
      fileText += answerExplanationTexts1;
    }
  }
  //Datei schreiben
  QFile file( exportFile );
  file.open( QFile::WriteOnly );
  QTextStream in( &file );
  in << fileText << endl;
  file.close();
}

QString ManageQuestionsMenu::makeLine( QList< QString > lineParts )
{
  if( lineParts.isEmpty() )
    return "";
  QString line( "" );
  for( int j = 0; j < lineParts.length() - 1; j++ )
    line += lineParts[ j ] + ";";
  line += lineParts[ lineParts.length() - 1 ];
  return line;
}

void ManageQuestionsMenu::openExportFileDialog( void )
{
  exportFile = QFileDialog::getSaveFileName( this, tr( "Export questions..." ), "", "CSV-file (*.csv)" );
  if( exportFile.isEmpty() )
    return;
  QStringList fileNameParts = exportFile.split( "." );
  if( fileNameParts[ fileNameParts.length() - 1 ] != "csv" )
    exportFile += ".csv";

  exportQuestions();
}
