import pygame
import sys
from usb_reader import USBReader
import subprocess

# ----------------------------
# USB START
# ----------------------------
usb = USBReader()

# ----------------------------
# PYGAME SETUP
# ----------------------------
pygame.init()
pygame.mouse.set_visible(False)

WIDTH, HEIGHT = 1440, 900
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("ARCAGEDDON UI")

bg_image = pygame.image.load("background.jpg").convert()
bg_image = pygame.transform.scale(bg_image, (WIDTH, HEIGHT))

clock = pygame.time.Clock()

# ----------------------------
# COLORS
# ----------------------------
BG = (18, 18, 18)
BTN = (70, 130, 200)
BTN_SELECTED = (255, 180, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 215, 0)

# ----------------------------
# FONTS
# ----------------------------
font = pygame.font.SysFont(None, 45)
title_font = pygame.font.SysFont("Press Start 2P", 80)

# ----------------------------
# BUTTON CLASS
# ----------------------------
class Button:
    def __init__(self, x, y, w, h, text):
        self.rect = pygame.Rect(x, y, w, h)
        self.text = text

    def draw(self, surface, selected=False):
        color = BTN_SELECTED if selected else BTN
        pygame.draw.rect(surface, color, self.rect, border_radius=12)

        label = font.render(self.text, True, WHITE)
        surface.blit(label, label.get_rect(center=self.rect.center))

# ----------------------------
# LAYOUT
# ----------------------------
menu_btn_w, menu_btn_h = 250, 80
btn_w, btn_h = 260, 80
spacing = 30

center_x = WIDTH // 2 - btn_w // 2
start_y = HEIGHT // 2 - 140

center_buttons = [
    Button(center_x, start_y, btn_w, btn_h, "PING"),
    Button(center_x, start_y + btn_h + spacing, btn_w, btn_h, "COBRA"),
    Button(center_x, start_y + 2 * (btn_h + spacing), btn_w, btn_h, "N.A."),
]

menu_button = Button(
    WIDTH - menu_btn_w - 30,
    HEIGHT - menu_btn_h - 30,
    menu_btn_w,
    menu_btn_h,
    "INPUTS CHECK"
)

# ----------------------------
# STATE
# ----------------------------
selected_index = 0
saved_index = 0
focus_mode = "CENTER"
game_process = None
input_process = None

# ----------------------------
# MAIN LOOP
# ----------------------------
running = True

while running:
    screen.blit(bg_image, (0, 0))

    pygame.draw.rect(
        screen,
        YELLOW,
        screen.get_rect(),
        width=10
    )

    # ----------------------------
    # CHECK GAME STATUS
    # ----------------------------
    if game_process is not None and game_process.poll() is not None:
        game_process = None

    # ----------------------------
    # USB INPUT (SAFE POLLING)
    # ----------------------------
    cmd = usb.read()

    # EMERGENCY EXIT COMMAND
    if cmd == "RASP":
        running = False

    if cmd:
        if focus_mode == "CENTER":

            if cmd == "UP":
                selected_index = (selected_index - 1) % len(center_buttons)

            elif cmd == "DOWN":
                selected_index = (selected_index + 1) % len(center_buttons)

            elif cmd == "RIGHT":
                saved_index = selected_index
                focus_mode = "MENU"

            elif cmd == "A":
                if game_process is None:
                    selected_game = center_buttons[selected_index].text

                    if selected_game == "PING":
                        game_process = subprocess.Popen(
                            [sys.executable, "game_1.py"],
                            stdin=subprocess.PIPE,
                            text=True
                        )

                    elif selected_game == "COBRA":
                        game_process = subprocess.Popen(
                            [sys.executable, "game_2.py"],
                            stdin=subprocess.PIPE,
                            text=True
                        )

                    elif selected_game == "N.A.":
                        game_process = subprocess.Popen(
                            [sys.executable, "game_3.py"],
                            stdin=subprocess.PIPE,
                            text=True
                        )

        elif focus_mode == "MENU":

            if cmd == "LEFT":
                focus_mode = "CENTER"
                selected_index = saved_index

            elif cmd == "A":
                if input_process is None or input_process.poll() is not None:

                    input_process = subprocess.Popen(
                        [sys.executable, "input.py"],
                        stdin=subprocess.PIPE,
                        text=True
                    )

    # ----------------------------
    # SEND INPUT TO INPUTS CHECK
    # ----------------------------
    if input_process is not None and input_process.poll() is None:
        try:
            input_process.stdin.write(cmd + "\n")
            input_process.stdin.flush()
        except:
            pass

    # ----------------------------
    # SEND INPUT TO GAME
    # ----------------------------
    if game_process is not None and game_process.poll() is None:
        try:
            if cmd:
                game_process.stdin.write(cmd + "\n")
                game_process.stdin.flush()
        except:
            pass

    # ----------------------------
    # EVENTS
    # ----------------------------
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False

    # ----------------------------
    # TITLE (RESTORED SHADOW EFFECT)
    # ----------------------------
    # bottom layer (furthest shadow) - RED
    shadow_red = title_font.render("ARCAGEDDON", True, (255, 0, 0))
    shadow_red_rect = shadow_red.get_rect(center=(WIDTH // 2 + 8, 108))
    screen.blit(shadow_red, shadow_red_rect)

    # middle layer - ORANGE
    shadow_orange = title_font.render("ARCAGEDDON", True, (255, 120, 0))
    shadow_orange_rect = shadow_orange.get_rect(center=(WIDTH // 2 + 4, 104))
    screen.blit(shadow_orange, shadow_orange_rect)

    # top layer (main text) - YELLOW
    main_text = title_font.render("ARCAGEDDON", True, YELLOW)
    main_rect = main_text.get_rect(center=(WIDTH // 2, 100))
    screen.blit(main_text, main_rect)

    # ----------------------------
    # DRAW UI
    # ----------------------------
    menu_button.draw(screen, selected=(focus_mode == "MENU"))

    for i, b in enumerate(center_buttons):
        b.draw(screen, selected=(focus_mode == "CENTER" and i == selected_index))

    pygame.display.flip()
    clock.tick(60)

# ----------------------------
# EXIT
# ----------------------------
usb.stop()
pygame.quit()
sys.exit()