import sys
import pygame
from multiprocessing import Process, Queue
from kivy.app import App

# ----------------------------
# GLOBAL STATE
# ----------------------------
NEXT_SCREEN = "menu"
GAME_SETTINGS = (1.0, 300)
GAME_QUEUE = Queue()

# ----------------------------
# PYGAME SPIEL
# ----------------------------
def run_pygame(spawn_rate, enemy_speed, queue):
    from owncar import Owncar
    from enemycar import Enemycar
    from road import Road

    SCREEN_WIDTH = 800
    SCREEN_HEIGHT = 600
    FPS = 60
    PLAYER_WIDTH = 60
    PLAYER_HEIGHT = 120
    ENEMY_WIDTH = 50
    ENEMY_HEIGHT = 100

    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Geisterfahrer")
    clock = pygame.time.Clock()

    road = Road(SCREEN_WIDTH, SCREEN_HEIGHT)
    own_car = Owncar(
        position=(SCREEN_WIDTH//2 - PLAYER_WIDTH//2, SCREEN_HEIGHT-PLAYER_HEIGHT-20),
        measures=(PLAYER_WIDTH, PLAYER_HEIGHT),
        stats=(0, 400)
    )

    enemies = []
    spawn_timer = 0
    running = True

    while running:
        dt = clock.tick(FPS)/1000

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running=False
                queue.put("quit")

        keys = pygame.key.get_pressed()
        own_car.move(keys, dt, SCREEN_WIDTH)

        spawn_timer += dt
        if spawn_timer >= spawn_rate:
            enemies.append(Enemycar.spawn(SCREEN_WIDTH, ENEMY_WIDTH, ENEMY_HEIGHT, enemy_speed))
            spawn_timer = 0

        for enemy in enemies[:]:
            enemy.move(dt)
            if own_car.crash(enemy):
                running=False
                queue.put("gameover")
            if enemy.y>SCREEN_HEIGHT:
                enemies.remove(enemy)

        road.update(dt)
        road.draw(screen)
        own_car.draw(screen)
        for enemy in enemies:
            enemy.draw(screen)

        pygame.display.flip()

    pygame.quit()
    if running:
        queue.put("menu")

# ----------------------------
# KIVY CALLBACKS
# ----------------------------
from screens.mainmenu import MainMenu
from screens.gameover import GameOverScreen
from kivy.app import App

def start_game(spawn, speed):
    global NEXT_SCREEN, GAME_SETTINGS
    NEXT_SCREEN = "game"
    GAME_SETTINGS = (spawn, speed)
    App.get_running_app().stop()

def quit_game():
    global NEXT_SCREEN
    NEXT_SCREEN = "quit"
    App.get_running_app().stop()

def restart_game():
    global NEXT_SCREEN
    NEXT_SCREEN = "game"
    App.get_running_app().stop()

def back_to_menu():
    global NEXT_SCREEN
    NEXT_SCREEN = "menu"
    App.get_running_app().stop()

# ----------------------------
# KIVY APP
# ----------------------------
class MenuApp(App):
    def build(self):
        global NEXT_SCREEN
        if NEXT_SCREEN=="gameover":
            screen = GameOverScreen()
            screen.restart_callback = restart_game
            screen.menu_callback = back_to_menu
            screen.quit_game_callback = quit_game
            return screen
        else:
            screen = MainMenu()
            screen.start_game_callback = start_game
            screen.quit_game_callback = quit_game
            return screen

# ----------------------------
# MAIN LOOP
# ----------------------------
if __name__=="__main__":
    while True:
        MenuApp().run()

        if NEXT_SCREEN=="quit":
            break

        if NEXT_SCREEN=="game":
            spawn, speed = GAME_SETTINGS
            p = Process(target=run_pygame, args=(spawn, speed, GAME_QUEUE))
            p.start()
            p.join()

            if not GAME_QUEUE.empty():
                result = GAME_QUEUE.get()
                if result=="gameover":
                    NEXT_SCREEN="gameover"
                elif result=="quit":
                    NEXT_SCREEN="quit"
                else:
                    NEXT_SCREEN="menu"
            else:
                NEXT_SCREEN="menu"

    print("Programm beendet.")
