from imgui_bundle import (
    imgui,
    immapp,
    imgui_md,
    ImVec2
)

from peewee import fn
from pathlib import Path
import subprocess, os, platform
from dbmodel import *
from .analyzer_state import AnalyzerState
from .plotter import plot_html

state = AnalyzerState()


@immapp.static(inited=False)
def ranking(class_id: int) -> None:
    if class_id < 1:
        return

    statics = ranking
    
    if not statics.inited:
        statics.class_id = class_id
        statics.data = [
            (student, Submission.select(fn.SUM(Submission.points)).where(Submission.student_id == student.id).scalar()) 
            for student in Student.select().where(Student.class_id == class_id)
        ]
        statics.data.sort(key = lambda tup: tup[1], reverse=True)
        statics.inited = True

    if statics.class_id != class_id:
        statics.inited = False
    
    imgui_md.render(f"# Ranking - {Class.get_by_id(statics.class_id).name}")
    imgui.text("")
    
    if imgui.begin_table("Ranking1", len(statics.data), imgui.TableFlags_.sizing_fixed_fit.value):
        for n, d in enumerate(statics.data, start=1):
            student, points = d 
            if points.is_integer():
                points = int(points)
            imgui.table_next_row()
            imgui.table_next_column()
            #imgui.set_next_item_width(-1)
            imgui.text(f"{n}. {student.prename} {student.surname} - {points} Points")
        imgui.end_table()

def class_graph() -> None:
    if db.is_closed():
        imgui.text("No DB loaded")
        return

    w, h = imgui.get_content_region_avail()

    if imgui.begin_child("Ranking", ImVec2(w*0.3, h*0.5), imgui.ChildFlags_.borders.value):
        ranking(state.class_id)
        imgui.end_child()
    
    imgui.same_line()

    if imgui.begin_child("Presentations", ImVec2(w*0.7, h*0.7), imgui.ChildFlags_.borders.value):
        html = Path("/storage/programming/Learnlytics/assets/covid_faelle_MeWi_2.html")
        plot_html(html)
        imgui.same_line()
        if imgui.button("Open in Browser"):
            # I Hate everything about it 
            if platform.system() == 'Darwin': # MacOS
                subprocess.Popen(('open', html))
            elif platform.system() == 'Windows': # Windows 
                os.startfile(html)
            else: # Linux & Variants
                subprocess.Popen(('xdg-open', html))
        imgui.end_child()
