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

from markdown_pdf import Section

from functools import reduce
import operator

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

    sections = list()
    text = ''

    filter = [(Student.study_id == study.id) for study in filter]
    expr = reduce(operator.or_, filter)
    students = list(Student.select().where(expr).where(Student.class_id == class_id))

    group_ids = set([student.group_id for student in students])
    group_filter = [(Group.id == id) for id in group_ids]
    if not group_filter:
        return [Section('# No Student found')]
    group_expr = reduce(operator.or_, group_filter)

    data = {
        group: [student for student in Student.select().where(Student.group_id == group.id).where(expr)]
        for group in Group.select().where(group_expr)
    }

    max_points = [lecture.points for lecture in Lecture.select().where(Lecture.class_id == next(iter(data.keys())).class_id)]
    
    n = 0
    for group, students in data.items():
        text += f'## {group.name}\n'
        text += f'#### Project: {group.project}\n'
        passed = '&check;' if group.has_passed else '&cross;'
        text += f'Passed Exam {passed}\n'
        text += '|Student|Study Program|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)
           
            text += f'|{student.prename} {student.surname}|{student.study.name}|{passed}|\n'
        text += '\n---\n\n'
        
        n += 1 
        if n == 2:
            sections.append(Section(text))
            n = 0 
            text = ''

    if text:
        sections.append(Section(text))
    
    return sections
