package se.kits.gakusei.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import se.kits.gakusei.content.repository.FactRepository;
import se.kits.gakusei.user.model.Event;
import se.kits.gakusei.user.model.ProgressTracking;
import se.kits.gakusei.user.model.User;
import se.kits.gakusei.user.repository.EventRepository;
import se.kits.gakusei.user.repository.ProgressTrackingRepository;
import se.kits.gakusei.user.repository.UserRepository;

import java.sql.Timestamp;

@Component
public class ProgressHandler {

    @Autowired
    private EventRepository eventRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ProgressTrackingRepository progressTrackingRepository;

    @Autowired
    private FactRepository factRepository;

    public void trackProgress(Event event) {

        User user = userRepository.findByUsername(event.getUser().getUsername());
        Timestamp latestTS = eventRepository.getLatestAnswerTimestamp(user.getUsername());
        String latestQuestion = eventRepository.getLatestQuestionForUser(user.getUsername());
        String nuggetID = factRepository.findNuggetsByFactData(latestQuestion).stream()
                .filter(n -> !n.isHidden())
                .findFirst().orElse(null).getId();

        if (nuggetID != null) {
            ProgressTracking pt = progressTrackingRepository.findProgressTrackingByUserAndNuggetID(user, nuggetID);
            if (pt != null) {
                if (event.getData().trim().equalsIgnoreCase("true")) {
                    pt.setCorrectCount(pt.getCorrectCount() + 1L);
                } else {
                    pt.setIncorrectCount(pt.getIncorrectCount() + 1L);
                }
            } else {
                pt = new ProgressTracking();
                pt.setUser(user);
                pt.setNuggetID(nuggetID);
                if (event.getData().trim().equalsIgnoreCase("true")) {
                    pt.setCorrectCount(1L);
                    pt.setIncorrectCount(0L);
                } else {
                    pt.setCorrectCount(0L);
                    pt.setIncorrectCount(1L);
                }
            }
            pt.setLatestTimestamp(latestTS);
            pt.setLatestResult(Boolean.parseBoolean(event.getData()));
            progressTrackingRepository.save(pt);
        }
    }
}

@@ -132,24 +132,69 @@
 .Component;%0A
+import se.kits.gakusei.content.model.Nugget;%0A
 import se.ki
@@ -1209,23 +1209,21 @@
     
-String
+Nugget
  nugget
-ID
  = f
@@ -1372,16 +1372,8 @@
 ull)
-.getId()
 ;%0A%0A 
@@ -1389,18 +1389,16 @@
  (nugget
-ID
  != null
@@ -1393,32 +1393,78 @@
 gget != null) %7B%0A
+            String nuggetID = nugget.getId();%0A
             Prog

fix null pointer hazard