001package edu.pdx.cs410J.grader;
002
003import com.google.common.annotations.VisibleForTesting;
004import com.opencsv.CSVReader;
005import com.opencsv.exceptions.CsvValidationException;
006
007import java.io.IOException;
008import java.io.Reader;
009
010public class D2LSurveyResponsesCSVParser {
011
012  @VisibleForTesting
013  int questionColumnIndex = -1;
014
015  @VisibleForTesting
016  int responseColumnIndex = -1;
017
018  private final SurveyResponsesFromD2L responses;
019
020  public D2LSurveyResponsesCSVParser(Reader reader) throws IOException {
021    CSVReader csv = new CSVReader( reader );
022    try {
023      String[] firstLine = csv.readNext();
024      extractColumnNamesFromFirstLineOfCsv(firstLine);
025
026      responses = new SurveyResponsesFromD2L();
027
028      String[] surveyLine;
029      while ((surveyLine = csv.readNext()) != null) {
030        addQuestionAndResponseFromLineOfCsv(surveyLine);
031      }
032
033    } catch (CsvValidationException ex) {
034      throw new IOException("While parsing CSV", ex);
035    }
036  }
037
038  private void addQuestionAndResponseFromLineOfCsv(String[] surveyLine) {
039    String question = getQuestionFromSurveyLine(surveyLine);
040    String response = getResponseFromSurveyLine(surveyLine);
041
042    this.responses.noteQuestionAndResponse(question, response);
043  }
044
045  private String getResponseFromSurveyLine(String[] surveyLine) {
046    return surveyLine[responseColumnIndex];
047  }
048
049  private String getQuestionFromSurveyLine(String[] surveyLine) {
050    return surveyLine[questionColumnIndex];
051  }
052
053  private void extractColumnNamesFromFirstLineOfCsv(String[] firstLine) {
054    for (int columnIndex = 0; columnIndex < firstLine.length; columnIndex++) {
055      String columnHeading = firstLine[columnIndex];
056      if ("Q Text".equals(columnHeading)) {
057        this.questionColumnIndex = columnIndex;
058
059      } else if ("Answer".equals(columnHeading)) {
060        this.responseColumnIndex = columnIndex;
061      }
062    }
063  }
064
065  public SurveyResponsesFromD2L getSurveyResponses() {
066    return this.responses;
067  }
068}