from imgui_bundle import (
    hello_imgui,
    immapp
)

from gui import (
    analyzer_layout,
    database_editor_layout,
    menu_bar,
    status_bar
)

from dbmodel import init_postgres, create_database, init_local
import getpass
from pathlib import Path

def main() -> None:
    """Main function to initialize and run the application."""
        
    # Load Database
    try:
        with open("./pickles/database_location.txt", "r") as f:
            file = f.read()
    except FileNotFoundError:
        file = str(Path.home() / "learnlytics.db")
        with open("./pickles/database_location.txt", "w") as f:
            f.write(file)
    
    name = getpass.getuser()
    create_database(name)
    init_postgres(name, 'postgres.cyperpunk.de', 'dergrumpf', '1P2h3i4lon$%', 5432)

    # Set Window Parameters
    runner_params = hello_imgui.RunnerParams()
    runner_params.app_window_params.window_title = "Analyzer"
    runner_params.imgui_window_params.menu_app_title = "Analyzer"
    runner_params.app_window_params.window_geometry.size = (1000, 900)
    runner_params.app_window_params.restore_previous_geometry = True
    runner_params.app_window_params.borderless = True
    runner_params.app_window_params.borderless_movable = True 
    runner_params.app_window_params.borderless_resizable = True 
    runner_params.app_window_params.borderless_closable = True 

    # Configure UI Elements
    runner_params.imgui_window_params.show_menu_bar = True
    runner_params.imgui_window_params.show_menu_app = False
    runner_params.imgui_window_params.show_menu_view = False
    runner_params.imgui_window_params.show_status_bar = True
    runner_params.callbacks.show_menus = lambda: menu_bar(runner_params)
    runner_params.callbacks.show_status = lambda: status_bar()

    # Application layout
    runner_params.imgui_window_params.default_imgui_window_type = (
        hello_imgui.DefaultImGuiWindowType.provide_full_screen_dock_space
    )
    runner_params.imgui_window_params.enable_viewports = True
    runner_params.docking_params = analyzer_layout()
    runner_params.alternative_docking_layouts = [
        database_editor_layout()
    ]

    # Save App Settings
    runner_params.ini_folder_type = hello_imgui.IniFolderType.app_user_config_folder
    runner_params.ini_filename = "Analyzer/Analyzer.ini"
    runner_params.docking_params.layout_condition = hello_imgui.DockingLayoutCondition.application_start

    # Run the Application
    add_ons_params = immapp.AddOnsParams()
    add_ons_params.with_markdown = True
    add_ons_params.with_implot = True
    add_ons_params.with_implot3d = True

    immapp.run(runner_params, add_ons_params)

if __name__ == "__main__":
    main()


