package de.thdeg.grademanager.gui;

import de.thdeg.grademanager.JpaService;
import de.thdeg.grademanager.model.Course;
import de.thdeg.grademanager.model.Student;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;

import java.io.IOException;
import java.util.List;

public class StudentCoursesController {

    private static Student student;

    public static void setStudent(Student student) {
        StudentCoursesController.student = student;
    }

    @FXML
    protected ListView<Course> coursesListView;

    @FXML
    protected void initialize() {
        if (student.getCoursesOfStudy() != null) {
            coursesListView.setItems(FXCollections.observableList(student.getCoursesOfStudy().getCourses()));
        }
        initEnrollmentsForCoursesOfStudy();
    }

    private void initEnrollmentsForCoursesOfStudy(){
        JpaService jpaService = JpaService.getInstance();
        List<Course> courses = jpaService.getCoursesForCoursesOfStudyFromDb(student.getCoursesOfStudy());
        Student s = jpaService.getStudentFromDb(student.getId());
        jpaService.runInTransaction(entityManager -> {entityManager.detach(s); return null;});
        s.clearEnrollmentsOldCoursesOfStudy(s.getCoursesOfStudy());
        s.initEnrollments(courses);
        jpaService.runInTransaction(entityManager -> {entityManager.merge(s); return null;});
    }

    @FXML
    protected void onCourseClick(MouseEvent event) throws IOException {
        StudentGradesController.setStudent(student);
        StudentGradesController.setCourse(coursesListView.getSelectionModel().getSelectedItem());
        SwitchWindowHelper.switchTo("Student Grades", event);
    }

    @FXML
    protected void switchToStudentDetails(ActionEvent event) throws IOException {
        StudentDetailsController.setStudent(student);
        SwitchWindowHelper.switchTo("Student Details", event);
    }
}