from imgui_bundle import imgui
from model import *

class SubmissionEditor:
    def __init__(self):
        super().__init__()
        self.current_lecture = 0
        self.current_student = 0
        self.points = 0

    def __call__(self, clas: Class):
        id = clas.id if clas else None
        lectures = Lecture.select().where(Lecture.class_id == id) if id else None
        students = Student.select().where(Student.class_id == id) if id else None

        with imgui.begin("Submission Editor", False, imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_COLLAPSE):
            imgui.text("Add Submission")
            
            if not lectures:
                imgui.text("No Lectures queried")
                return

            if not students:
                imgui.text("No Students queried")
                return

            _, self.current_lecture = imgui.combo("Lecture", self.current_lecture, [f"{l.title} ({l.points})" for l in lectures])
            _, self.current_student = imgui.combo("Student", self.current_student, [f"{s.prename} {s.surname}" for s in students])
            
            if self.points < 0:
                self.points = 0

            max = lectures[self.current_lecture].points
            if self.points > max:
                self.points = max
    
            _, self.points = imgui.input_float("Points", self.points, format='%.1f', step=0.5, step_fast=1.0)

            if imgui.button("Add"):
                if not Submission.select().where(
                        Submission.student_id == students[self.current_student].id and
                        Submission.lecture_id == lectures[self.current_lecture].id
                    ):
                    Submission.create(
                        student_id=students[self.current_student].id,
                        lecture_id=lectures[self.current_lecture].id,
                        points=self.points
                    )
            
            imgui.same_line()

            if imgui.button("Update"):
                submission = Submission.select().where(
                                Submission.student_id == students[self.current_student].id and
                                Submission.lecture_id == lectures[self.current_lecture].id
                                ).get()
                submission.points = self.points
                submission.save()
            
            imgui.same_line()

            if imgui.button("Delete"):
                Submission.delete().where(
                    Submission.student_id == students[self.current_student].id and
                    Submission.lecture_id == lectures[self.current_lecture].id
                    ).execute()
