package de.thdeg.grademanager.gui;

import de.thdeg.grademanager.JpaService;
import de.thdeg.grademanager.model.CoursesOfStudy;
import de.thdeg.grademanager.model.Student;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;

import java.io.IOException;

import static de.thdeg.grademanager.gui.MainController.coursesOfStudyList;

public class StudentDetailsController {

    private static Student student;

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


    @FXML
    protected ComboBox<CoursesOfStudy> coursesOfStudyComboBox;

    @FXML
    protected TextField gender;
    @FXML
    protected TextField firstName;
    @FXML
    protected TextField lastName;
    @FXML
    protected TextField placeOfResidence;
    @FXML
    protected TextField birthPlace;

    @FXML
    protected TextField coursesOfStudy;

    @FXML
    protected TextField semester;

    @FXML
    protected TextField studentID;
    @FXML
    protected TextField officialEmail;

    @FXML
    protected void initialize() {
        if (student != null) {
            gender.setText(student.getGender().toString());
            firstName.setText(student.getFirstName());
            lastName.setText(student.getLastName());
            placeOfResidence.setText(student.getPlaceOfResidence());
            birthPlace.setText(student.getBirthPlace());
            if (student.getCoursesOfStudy() != null){
                coursesOfStudy.setText(student.getCoursesOfStudy().getName());
            }
            semester.setText(Integer.toString(student.getSemester()));
            officialEmail.setText(student.getOfficialEmail());
            studentID.setText(Integer.toString(student.getId()));
            coursesOfStudyComboBox.setItems(coursesOfStudyList);
        }
    }

    @FXML
    protected void assignCoursesOfStudy(ActionEvent event) {
        student.setCoursesOfStudy(coursesOfStudyComboBox.getValue());
        JpaService jpaService = JpaService.getInstance();
        jpaService.runInTransaction(entityManager -> {entityManager.merge(student); return null;});
        initialize();
    }

    @FXML
    protected void switchToMain(ActionEvent event) throws IOException {
        SwitchWindowHelper.switchTo("Main", event);
    }
}