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

import numpy as np
from peewee import fn
from pathlib import Path

from dbmodel import *
from grader import get_gradings, get_grader
from pdf import *
from .analyzer_state import AnalyzerState 
from .plotter import plot_bar_line_percentage 
from .document_creator import load_properties

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


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

    if reset:
        statics.inited = False

    if not statics.inited:
        statics.student = Student.get_by_id(student_id)
        statics.study = Study.get_by_id(statics.student.study.id)

        points = [sub.points for sub in Submission.select().where(Submission.student_id == student_id)]
        max_points = [lecture.points for lecture in Lecture.select().where(Lecture.class_id == statics.student.class_id)]
        statics.has_passed = get_grader(statics.student.grader).get_final_grade(points, max_points, False)
        statics.inited = True

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

    imgui_md.render_unindented(f"# {statics.student.prename} {statics.student.surname} - {statics.has_passed}")
    imgui_md.render_unindented(f"Degree Program: **{statics.study.name}**")
    imgui.same_line()
    if imgui.button("Create Summary"):
        properties = load_properties()
        pdf, css = get_pdf(statics.student.class_id)
        sections = get_pdf_student(statics.student.id, properties.author, properties.logo)
        for section in sections:
            pdf.add_section(section, user_css = css)
        save = properties.save_dir / (properties.file_name + '.pdf')
        pdf.save(save)

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

    if student_id < 1:
        imgui_md.render_unindented("# Student Analyzer")
        return
    
    if reset:
        statics.inited = False

    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)

@immapp.static(inited=False)
def dialog(student_id: int) -> None:
    imgui_md.render_unindented("# Student Attributes")

    if student_id < 1:
        return 
    
    statics = dialog

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

        statics.prename = statics.student.prename
        statics.surname = statics.student.surname

        statics.genders = ["Male", "Female", "Diverse"]
        statics.sex = statics.genders.index(statics.student.sex)
        
        statics.studys = list(Study.select())
        s = Study.get_by_id(statics.student.study_id)
        statics.study = statics.studys.index(s)

        statics.groups = list(Group.select().where(Group.class_id == statics.student.class_id))
        g = Group.get_by_id(statics.student.group_id)
        statics.group = statics.groups.index(g)

        statics.graders = [grade.alt_name for grade in get_gradings()]
        statics.grader = statics.graders.index(statics.student.grader)

        statics.inited = True

    if statics.student_id != student_id:
        statics.inited = False
    
    if imgui.begin_table("Attributes", 2):#, imgui.TableFlags_.sizing_fixed_fit.value):
        imgui.table_next_row()
        imgui.table_next_column()
        imgui.text("First Name")
        imgui.table_next_column()
        _, statics.prename = imgui.input_text("##First Name", statics.prename)

        imgui.table_next_row()
        imgui.table_next_column()
        imgui.text("Last Name")
        imgui.table_next_column()
        _, statics.surname = imgui.input_text("##Last Name", statics.surname)
       
        imgui.table_next_row()
        imgui.table_next_column()
        imgui.text("Sex")
        imgui.table_next_column()
        _, statics.sex = imgui.combo("##Sex", statics.sex, statics.genders)
        
        imgui.table_next_row()
        imgui.table_next_column()
        imgui.text("Study Program")
        imgui.table_next_column()
        _, statics.study = imgui.combo("##Study", statics.study, [s.name for s in statics.studys])
        
        imgui.table_next_row()
        imgui.table_next_column()
        imgui.text("Group")
        imgui.table_next_column()
        _, statics.group = imgui.combo("##Group", statics.group, [g.name for g in statics.groups])
        
        imgui.table_next_row()
        imgui.table_next_column()
        imgui.text("Grader")
        imgui.table_next_column()
        _, statics.grader = imgui.combo("##Grader", statics.grader, statics.graders)
 
        imgui.end_table()

    if imgui.button("Save"):
        statics.student.prename = statics.prename
        statics.student.surname = statics.surname
        statics.student.sex = statics.genders[statics.sex]
        statics.student.study_id = statics.studys[statics.study].id
        statics.student.group_id = statics.groups[statics.group].id
        statics.student.grader = get_grader(statics.graders[statics.grader]).alt_name
        statics.student.save()
        statics.inited = False
        return True 

    return False


@immapp.static(inited=False)
def lecture_lists(student_id: int) -> None:
    imgui_md.render_unindented("# Lectures")

    if student_id < 1:
        return
    
    statics = lecture_lists
    if not statics.inited:
        statics.student_id = student_id
        statics.student = Student.get_by_id(student_id)
        statics.subs = list(Submission.select().where(Submission.student_id == statics.student.id))
        statics.inited = True

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

    if imgui.begin_table("Lecture List", 2, imgui.TableFlags_.none.value):
        for sub in statics.subs:
            imgui.table_next_row()
            imgui.table_next_column()
            imgui.text(sub.lecture_id.title)
            imgui.table_next_column()
            imgui.text(f'{int(sub.points) if sub.points.is_integer() else sub.points}/{sub.lecture_id.points} Points')
        imgui.end_table()

@immapp.static(inited=False)
def student_graph() -> None:
    if db.is_closed():
        imgui.text("No DB loaded")
        return
    
    statics = student_graph
    if not statics.inited:
        statics.reset = False
        statics.inited = True

    w, h = imgui.get_content_region_avail()

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

    if imgui.begin_child("Dialog", ImVec2(w*0.4, h*0.34), imgui.ChildFlags_.borders.value):
        statics.reset = dialog(state.student_id)
        imgui.end_child()

    imgui.same_line()

    if imgui.begin_child("Lectures", ImVec2(w*0.3, h*0.34), imgui.ChildFlags_.borders.value):
        lecture_lists(state.student_id)
        imgui.end_child()
