import imgui
import glfw
import OpenGL.GL as gl
from imgui.integrations.glfw import GlfwRenderer
from datatypes import *
from view import View

def impl_glfw_init(window_name="Grapher Tool", width=1280, height=720):
    if not glfw.init():
        print("Could not initialize OpenGL context")
        exit(1)

    # OS X supports only forward-compatible core profiles from 3.2
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(int(width), int(height), window_name, None, None)
    glfw.make_context_current(window)

    if not window:
        glfw.terminate()
        print("Could not initialize Window")
        exit(1)

    return window

class GUI(object):
    def __init__(self):
        super().__init__() 
    
        # Window States
        self.window = impl_glfw_init()
        gl.glClearColor(*COLOR_BACKGROUND)
        imgui.create_context()
        self.impl = GlfwRenderer(self.window)
        self.io = imgui.get_io()

        # Global GUI Setting
        win_w, win_h = glfw.get_window_size(self.window)
        fb_w, fb_h = glfw.get_framebuffer_size(self.window)
        font_scaling_factor = max(float(fb_w) / win_w, float(fb_h) / win_h) 
        font_size_in_pixels = 30
        self.io.fonts.add_font_from_file_ttf("assets/MPLUSRounded1c-Regular.ttf", font_size_in_pixels * font_scaling_factor)
        self.io.font_global_scale /= font_scaling_factor

        self.view = View()
        self.loop()
    
    def header(self):
        imgui.set_next_window_size(io.display_size.x, io.display_size.y*0.03)
        imgui.set_next_window_position(0, io.display_size.y*0.02)

        with imgui.begin("HEADER", False, imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_COLLAPSE | imgui.WINDOW_NO_TITLE_BAR):
            imgui.set_window_font_scale(1.3)
            text = "Student Analyzer"
            ww = imgui.get_window_size().x
            tw = imgui.calc_text_size(text).x
            imgui.set_cursor_pos_x((ww - tw) * 0.5)
            imgui.text("Student Analyzer")
 
    def loop(self):
        while not glfw.window_should_close(self.window):
            glfw.poll_events()
            self.impl.process_inputs()
            imgui.new_frame()
            
            self.view()

            #imgui.show_test_window()

            imgui.render()

            gl.glClearColor(*COLOR_BACKGROUND)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)

            self.impl.render(imgui.get_draw_data())
            glfw.swap_buffers(self.window)

        self.impl.shutdown()
        glfw.terminate()


if __name__ == "__main__":

    gui = GUI()
