package edu.pdx.cs410J.grader.poa;

import com.google.common.eventbus.Subscribe;
import edu.pdx.cs410J.grader.GradeBook;
import edu.pdx.cs410J.grader.XmlDumper;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

import java.io.File;
import java.io.IOException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class GradeBookLoaderTest extends EventBusTestCase {

  @Override
  public void setUp() {
    super.setUp();
    new GradeBookLoader(this.bus);
  }

  @Test
  public void gradeBookLoadedOnLoadGradeBookEvent() throws IOException {
    String gradeBookName = "Test Grade Book";
    File file = writeGradeBookToFile(gradeBookName);

    GradeBookLoadedHandler handler = mock(GradeBookLoadedHandler.class);
    this.bus.register(handler);

    this.bus.post(new LoadGradeBook(file));

    ArgumentCaptor<GradeBookLoaded> event = ArgumentCaptor.forClass(GradeBookLoaded.class);
    verify(handler).handle(event.capture());

    assertThat(event.getValue().getGradeBook().getClassName(), equalTo(gradeBookName));
  }

  private File writeGradeBookToFile(String gradeBookName) throws IOException {
    File file = File.createTempFile("testGradeBook", "xml");

    GradeBook book = new GradeBook(gradeBookName);
    XmlDumper dumper = new XmlDumper(file);
    dumper.dump(book);

    return file;
  }

  private interface GradeBookLoadedHandler {
    @Subscribe
    void handle(GradeBookLoaded event);
  }

}

@@ -316,16 +316,57 @@
 rtThat;%0A
+import static org.hamcrest.Matchers.any;%0A
 import s
@@ -1591,10 +1591,704 @@
 );%0A  %7D%0A%0A
+  @Test%0A  public void unhandledExceptionEventPublishedWhenLoadingBadGradeBook() throws IOException %7B%0A    File badFile = File.createTempFile(%22badGradeBook%22, %22xml%22);%0A%0A    UnhandledExceptionEventHandler handler = mock(UnhandledExceptionEventHandler.class);%0A    this.bus.register(handler);%0A%0A    this.bus.post(new LoadGradeBook(badFile));%0A%0A    ArgumentCaptor%3CUnhandledExceptionEvent%3E event = ArgumentCaptor.forClass(UnhandledExceptionEvent.class);%0A    verify(handler).handle(event.capture());%0A%0A    assertThat(event.getValue().getUnhandledException(), any(Throwable.class));%0A  %7D%0A%0A  private interface UnhandledExceptionEventHandler %7B%0A    @Subscribe%0A    void handle(UnhandledExceptionEvent event);%0A  %7D%0A
 %7D%0A

Make sure that an UnhandledExceptionEvent is fired when a grade book file cannot be parsed.