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

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
    if imgui.button("New Class"):
        imgui.open_popup("NewC")
    new_class()
    
    classes = Class.select()
    if classes.count() < 1:
        return -1

    labels = (c.name for c in classes)
    _, statics.selector = imgui.combo("##Classes", statics.selector, list(labels))

    current = classes[statics.selector].id

    imgui.same_line()

    if imgui.button("Delete Class"):
        imgui.open_popup("DeleteC")
    if delete_class(current):
        statics.inited = False

    imgui.separator()
    return current 

@immapp.static(inited=False)
def new_class() -> None:
    statics = new_class

    if not statics.inited:
        statics.name = str()
        statics.inited = True

    center = imgui.get_main_viewport().get_center()
    imgui.set_next_window_pos(center, imgui.Cond_.appearing.value, ImVec2(0.5, 0.5))
    
    if imgui.begin_popup("NewC"):
        imgui_md.render_unindented("# New Class")
    
        _, statics.name = imgui.input_text("Name", statics.name)

        if imgui.button("Add"):
            clas = Class.create(name=statics.name)
            Study.get_or_create(name='Student')
            Group.create(
                name="NoGroup",
                project="NoProject",
                has_passed=False,
                class_id = clas.id
            )
            imgui.close_current_popup()
            statics.inited = False

        imgui.same_line()

        if imgui.button("Cancel"):
            imgui.close_current_popup()
            statics.inited = False

        imgui.end_popup()


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

    if not statics.inited:
        statics.class_id = class_id
        statics.data = {
            "Students": Student.select().where(Student.class_id == class_id).count(),
            "Groups": Group.select().where(Group.class_id == class_id).count(),
            "Lectures": Lecture.select().where(Lecture.class_id == class_id).count(),
            "Submissions": Submission.select().where(Submission.class_id == class_id).count()
        }
        statics.inited = True
        statics.ret = False

    if statics.class_id != class_id:
        statics.inited = False
    
    center = imgui.get_main_viewport().get_center()
    imgui.set_next_window_pos(center, imgui.Cond_.appearing.value, ImVec2(0.5, 0.5))
    
    size = imgui.get_main_viewport().size
    imgui.set_next_window_size(ImVec2(size.x * 0.1, size.y * 0.25))
    
    if imgui.begin_popup("DeleteC"):
        imgui_md.render_unindented("# Delete Class")
        imgui_md.render_unindented("**Are you sure?**")
        imgui_md.render_unindented("This Operation deletes:")
        
        if imgui.begin_table("Attributes", len(statics.data)):
            for attr, count in statics.data.items():
                imgui.table_next_row()
                imgui.table_next_column()
                imgui.text(attr)
                imgui.table_next_column()
                imgui.text(str(count))

            imgui.end_table()


        if imgui.button("Delete"):
            Submission.delete().where(Submission.class_id == statics.class_id).execute()
            Group.delete().where(Group.class_id == statics.class_id).execute()
            Lecture.delete().where(Lecture.class_id == statics.class_id).execute()
            Student.delete().where(Student.class_id == statics.class_id).execute()
            Class.get_by_id(statics.class_id).delete_instance()
            imgui.close_current_popup()
            statics.inited = False
            statics.ret = True

        imgui.same_line()

        if imgui.button("Cancel"):
            imgui.close_current_popup()
            statics.inited = False

        imgui.end_popup()

    return statics.ret


@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.counter = 0
        statics.inited = True

    if statics.class_id != class_id:
        statics.inited = False
    
    if statics.counter > 60:
        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.counter = 0

    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()

    statics.counter += 1
    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)
