from dbmodel import *
from grader import get_grader
from markdown_pdf import Section
from .utils import error

def create_study_pdf(class_id: int, filter: list[Study]) -> list[Section]:
    if not filter:
        return error()

    sections = list()
    text = ''

    data = {
        study: list(Student.select().where(Student.study_id == study.id).where(Student.class_id == class_id))
        for study in filter
    }

    max_points = [lecture.points for lecture in Lecture.select().where(Lecture.class_id == next(iter(data.values()))[0].class_id)]
    max = sum(max_points)
    
    for study, students in data.items():
        text += f'## {study.name}\n'
        text += f'#### Number of Students: {Student.select().where(Student.study_id == study.id).count()}\n'
        text += '|Student|Points|Percentage|Passed?|\n'
        text += '|-|-|-|-|\n'

        for student in students:                    

            grader = get_grader(student.grader)
            overall_points = [sub.points for sub in Submission.select().where(Submission.student_id == student.id)]
            passed = grader.get_final_grade(overall_points, max_points)
            points = sum(overall_points)
            points = int(points) if points.is_integer() else points
            
            text += f'|{student.prename} {student.surname}|{points}/{max}|{points/max:.1%}|{passed}|\n'
        
        sections.append(Section(text))
        text = ''

    return sections
