import time
import pygame
from pygame.locals import *
from Palima.Object import GetObject, RegisterGameObject, RenderAllGameObjects, GetCamera, RegisterCamera
from Palima.Window import Window
from Palima.Input import update_input


def run():
    window = Window()
    window.show()
    
    # Initialize input system
    from Input import _input_manager
    _input_manager.update()
    
    # Call start() for all registered game objects
    for obj_name in list(GetObject.__globals__.get('_game_objects', {}).keys()):
        obj = GetObject(obj_name)
        if obj:
            obj.start()
    
    # Call start() for all registered cameras
    for cam_name in list(GetCamera.__globals__.get('_cameras', {}).keys()):
        cam = GetCamera(cam_name)
        if cam:
            cam.start()
    
    window.is_running = True
    
    try:
        while window.is_running:
            # Update input system
            update_input()
            
            # Handle window close events
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    window.is_running = False
            
            # Check ESC key for exit
            from Input import listen
            if listen("ESCAPE"):
                window.is_running = False
            
            # Call update() for all registered game objects
            for obj_name in list(GetObject.__globals__.get('_game_objects', {}).keys()):
                obj = GetObject(obj_name)
                if obj:
                    obj.update()
            
            # Call update() for all registered cameras
            for cam_name in list(GetCamera.__globals__.get('_cameras', {}).keys()):
                cam = GetCamera(cam_name)
                if cam:
                    cam.update()
            
            # Update window and render 3D scene
            window.update()
            
            # Simple frame rate control
            time.sleep(0.016)  # ~60 FPS
    
    except KeyboardInterrupt:
        pass
    finally:
        # Call finish() for all registered game objects
        for obj_name in list(GetObject.__globals__.get('_game_objects', {}).keys()):
            obj = GetObject(obj_name)
            if obj:
                obj.finish()
        
        # Call finish() for all registered cameras
        for cam_name in list(GetCamera.__globals__.get('_cameras', {}).keys()):
            cam = GetCamera(cam_name)
            if cam:
                cam.finish()
        
        window.close()
