import numpy as np
from imgui_bundle import imgui

from model import *

class StudentRanking:
    def __init__(self):
        super().__init__()

    def __call__(self):
        students = Student.select().where(Student.class_id == 1)
        lectures = Lecture.select().where(Lecture.class_id == 1)

        overall_points = sum([l.points for l in lectures]) 
    
        ranking = list()
        avg = list()
        for s in students:
            rank = sum([sub.points for sub in Submission.select().where(Submission.student_id == s.id)])/overall_points
            ranking.append((f"{s.prename} {s.surname}", rank))
            avg.append(rank)
        ranking = sorted(ranking, key=lambda x: x[1], reverse=True)
        avg = sum(avg)/len(avg)

        flag = True

        with imgui.begin("Student Ranking", False, imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_COLLAPSE):
            for n, rank in enumerate(ranking, start=1):
                if rank[1] < avg and flag:
                    imgui.separator()
                    flag = False

                imgui.text(f"{n}. {rank[0]} {rank[1]:.1%}")

            imgui.separator()
            imgui.text(f"Average: {avg:.1%}")

