001package edu.pdx.cs410J.grader.canvas;
002
003import com.opencsv.CSVWriter;
004import edu.pdx.cs410J.grader.gradebook.Assignment;
005import edu.pdx.cs410J.grader.gradebook.GradeBook;
006import edu.pdx.cs410J.grader.gradebook.Student;
007
008import java.io.Writer;
009import java.util.ArrayList;
010import java.util.List;
011import java.util.function.Function;
012
013public class CanvasGradesCSVGenerator implements CanvasGradesCSVColumnNames {
014  private final Writer writer;
015
016  public CanvasGradesCSVGenerator(Writer writer) {
017    this.writer = writer;
018  }
019
020  public void generate(GradeBook book) {
021    CSVWriter csv = new CSVWriter(writer);
022    writeHeaderRow(book, csv);
023    writePossiblePointsRow(book, csv);
024    writeStudentRows(book, csv);
025  }
026
027  private void writePossiblePointsRow(GradeBook book, CSVWriter csv) {
028    List<String> line = new ArrayList<>();
029    line.add("Possible Points");
030    line.add("");  // Login ID
031    line.add("");  // Section
032
033    addCellsForEachAssignment(book, line, this::getPossiblePoints);
034
035    csv.writeNext(line.toArray(new String[0]));
036
037  }
038
039  private String getPossiblePoints(Assignment assignment) {
040    return String.valueOf(assignment.getPoints());
041  }
042
043  private void writeStudentRows(GradeBook book, CSVWriter csv) {
044    book.studentsStream().forEach(student -> writeStudentRow(book, student, csv));
045  }
046
047  private void writeStudentRow(GradeBook book, Student student, CSVWriter csv) {
048    csv.writeNext(getStudentLine(book, student));
049  }
050
051  private String[] getStudentLine(GradeBook book, Student student) {
052    return new String[] {
053      getStudentName(student),
054      student.getCanvasId(),
055      book.getSectionName(student.getEnrolledSection())
056    };
057  }
058
059  private String getStudentName(Student student) {
060    return student.getLastName() + ", " + student.getFirstName();
061  }
062
063  private void writeHeaderRow(GradeBook book, CSVWriter csv) {
064    List<String> line = new ArrayList<>();
065    line.add(STUDENT_COLUMN);
066    line.add(ID_COLUMN);
067    line.add(SECTION_COLUMN);
068
069    addCellsForEachAssignment(book, line, this::getAssignmentHeaderCell);
070
071    csv.writeNext(line.toArray(new String[0]));
072  }
073
074  private void addCellsForEachAssignment(GradeBook book, List<String> line, Function<Assignment, String> function) {
075    book.getAssignmentNames().stream().map(book::getAssignment).forEach(assignment -> {
076      line.add(function.apply(assignment));
077    });
078  }
079
080  private String getAssignmentHeaderCell(Assignment assignment) {
081    return assignment.getName() + " (" + assignment.getCanvasId() + ")" ;
082  }
083}