001package edu.pdx.cs410J.grader;
002
003import com.google.common.io.ByteStreams;
004import edu.pdx.cs410J.ParserException;
005import edu.pdx.cs410J.grader.gradebook.GradeBook;
006import edu.pdx.cs410J.grader.gradebook.Student;
007import edu.pdx.cs410J.grader.gradebook.XmlStudentParser;
008import jakarta.mail.Message;
009
010import java.io.File;
011import java.io.FileOutputStream;
012import java.io.IOException;
013import java.io.InputStream;
014import java.util.Collections;
015
016public class SurveySubmissionsProcessor extends StudentEmailAttachmentProcessor {
017  public SurveySubmissionsProcessor(File directory, GradeBook gradeBook) {
018    super(directory, gradeBook);
019  }
020
021  @Override
022  public Iterable<? extends String> getSupportedContentTypes() {
023    return Collections.singleton("text/xml");
024  }
025
026  @Override
027  public String getEmailFolder() {
028    return "Student Surveys";
029  }
030
031  @Override
032  public void processAttachment(Message message, String fileName, InputStream inputStream, String contentType) {
033    debug("    File name: " + fileName);
034    debug("    InputStream: " + inputStream);
035
036    File file = new File(directory, fileName);
037    try {
038
039      if (file.exists()) {
040        warnOfPreExistingFile(file);
041        return;
042      }
043
044      ByteStreams.copy(inputStream, new FileOutputStream(file));
045    } catch (IOException ex) {
046      logException("While writing \"" + fileName + "\" to \"" + directory + "\"", ex);
047    }
048
049    addStudentFromFileToGradeBook(file, gradeBook);
050  }
051
052  private void addStudentFromFileToGradeBook(File file, GradeBook gradeBook) {
053    Student student;
054
055    try {
056      XmlStudentParser parser = new XmlStudentParser(file);
057      student = parser.parseStudent();
058
059    } catch (IOException | ParserException ex) {
060      logException("While parsing \"" + file + "\"", ex);
061      return;
062    }
063
064    if (gradeBook.containsStudent(student.getId())) {
065      warn("Student \"" + student.getId() + "\" already exists in " + gradeBook.getClassName());
066      return;
067    }
068
069    gradeBook.addStudent(student);
070
071    info("Added " + student.getFullName() + " to " + gradeBook.getClassName());
072
073    logNotesAboutStudent(student);
074  }
075
076  private void logNotesAboutStudent(Student student) {
077    student.getNotes().forEach((note) -> info("  " + note));
078  }
079
080  private void warnOfPreExistingFile(File file) {
081    warn("Not processing existing file \"" + file + "\"");
082  }
083
084}