import steamvr
from steamvr import LighthouseConsole
from steamvr import SteamVR
import glfw
import OpenGL.GL as GL
import imgui
from imgui.integrations.glfw import GlfwRenderer

lhc = LighthouseConsole.create()
vr = SteamVR()


def gui():
    global lhc
    global vr
    if imgui.button("Set to 90hz (1920x1920)"):
        device_config = lhc.download_config()
        if steamvr.get_resolution(device_config) != (1920, 1920):
            device_config = steamvr.set_resolution(device_config, 1920, 1920)
            lhc.upload_config(device_config)

    if imgui.button("Set to 75hz (2544x2544)"):
        device_config = lhc.download_config()
        if steamvr.get_resolution(device_config) != (2544, 2544):
            device_config = steamvr.set_resolution(device_config, 2544, 2544)
            lhc.upload_config(device_config)

    if imgui.button("Restart SteamVR"):
        try:
            vr.restart()
        except steamvr.KillingOtherInstance:
            pass


def main():
    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()

        imgui.new_frame()

        gui()

        GL.glClearColor(73 / 255, 75 / 255, 92 / 255, 1)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()


def impl_glfw_init():
    width, height = 1280, 720
    window_name = "ByD control panel"

    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


if __name__ == "__main__":
    main()
