from imgui_bundle import (
    imgui,
    immapp,
    imgui_md
)

from dbmodel import *

from .analyzer_state import AnalyzerState 

state = AnalyzerState()

@immapp.static(inited=False)
def class_selector() -> int:
    statics = class_selector

    if not statics.inited:
        statics.selector = 0
        statics.inited = True

    labels = (c.name for c in Class.select())
    _, statics.selector = imgui.combo("##Classes", statics.selector, list(labels))
    imgui.separator()
    return Class.select()[statics.selector].id

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

    if not statics.inited:
        statics.class_id = class_id
        statics.data = {
            group: list(Student.select().where(Student.group_id == group.id))
            for group in Group.select().where(Group.class_id == statics.class_id)
        }
        statics.selected = -1
        statics.ret = (-1, -1)
        statics.flags = imgui.TreeNodeFlags_.none.value
        statics.inited = True

    if statics.class_id != class_id:
        statics.inited = False
    
    if imgui.button("Expand"):
        statics.flags = imgui.TreeNodeFlags_.default_open.value

    imgui.same_line()

    if imgui.button("Collapse"):
        statics.flags = imgui.TreeNodeFlags_.none.value

    n = 0
    for group, students in statics.data.items():
        if imgui.tree_node_ex(f"{group.name} -  {group.project}", statics.flags):
            for student in students:
                changed, _ = imgui.selectable(f"{student.prename} {student.surname}", statics.selected == n)
                if changed:
                    statics.selected = n
                    statics.ret = (group.id, student.id)
                n += 1
            n += 1
            imgui.tree_pop()

    return statics.ret

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

    state.class_id = class_selector()
    state.group_id, state.student_id = tree(state.class_id)
