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

import numpy as np
from peewee import fn

from dbmodel import *

from .analyzer_state import AnalyzerState 
from .plotter import plot_bar_line_percentage 

state = AnalyzerState()
PROGRESS_BAR_COLOR = ImVec4(190, 190, 40, 255)/255


@immapp.static(inited=False)
def header(student_id: int) -> None:
    statics = header
    
    if student_id < 1:
        return

    if not statics.inited:
        statics.student = Student.get_by_id(student_id)
        statics.inited = True

    if statics.student.id != student_id:
        statics.inited = False

    imgui_md.render(f"# {statics.student.prename} {statics.student.surname}")

@immapp.static(inited=False)
def plot(student_id: int) -> None:
    statics = plot 

    if student_id < 1:
        return

    if not statics.inited:
        statics.student = Student.get_by_id(student_id)
        submissions = Submission.select().where(Submission.student_id == statics.student.id)
        lectures = Lecture.select().where(Lecture.class_id == statics.student.class_id)
        
        statics.labels = [l.title for l in lectures]
        statics.data = np.array([sub.points/l.points for sub, l in zip(submissions, lectures)], dtype=np.float32) * 100
        statics.avg = np.mean(statics.data)/100
        statics.points = Submission.select(fn.SUM(Submission.points)).where(Submission.student_id == statics.student.id).scalar()
        if statics.points.is_integer():
            statics.points = int(statics.points)
        statics.max_points = Lecture.select(fn.SUM(Lecture.points)).where(Lecture.class_id == statics.student.class_id).scalar()
        statics.inited = True 

    if statics.student.id != student_id:
        statics.inited = False
    
    imgui.text(f"{statics.points}/{statics.max_points}")
    imgui.same_line()
    w, h = imgui.get_window_size()
    imgui.push_style_color(imgui.Col_.plot_histogram.value, PROGRESS_BAR_COLOR)
    imgui.progress_bar(statics.avg, ImVec2(w*0.9, h*0.07), f"{statics.avg:.1%}")
    imgui.pop_style_color()
    plot_bar_line_percentage(statics.data, statics.labels, statics.avg*100)

def student_graph() -> None:
    if db.is_closed():
        imgui.text("No DB loaded")
        return
    
    w, h = imgui.get_content_region_avail()

    if imgui.begin_child("Header", ImVec2(w, h*0.5), imgui.ChildFlags_.borders.value):
        header(state.student_id)
        plot(state.student_id)
        imgui.end_child()
    imgui.separator()
