#!/usr/bin/env python3

import sys
import os
import sdl2
import sdl2.ext

class KeyLogger:
    def __init__(self):
        # Initialize SDL2
        sdl2.ext.init(joystick=True, video=True, audio=False)
        # Initialize joystick support
        sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
        sdl2.SDL_JoystickOpen(0)
        self.window = sdl2.ext.Window("Key Logger", size=(640, 480))
        self.window.show()
        self.running = True
        self.key_down = True
        self.font = sdl2.ext.FontManager("assets/decterm.ttf", size=24)

    def run(self):
        # Main loop
        
        while self.running:
            # Handle SDL events
            events = sdl2.ext.get_events()
            for event in events:
                self.event = event.type
                if event.type == sdl2.SDL_KEYDOWN:
                    keycode = event.key.keysym.sym
                    # Log keycode to file
                    self.message  = f"Key pressed: {sdl2.SDL_GetKeyName(keycode).decode('utf-8')}"
                elif event.type == sdl2.SDL_KEYUP:
                    keycode = event.key.keysym.sym
                    # Log keycode to file
                    self.message = f"Key released: {sdl2.SDL_GetKeyName(keycode).decode('utf-8')}"
                elif event.type == sdl2.SDL_JOYBUTTONDOWN:
                    button = event.jbutton.button
                    self.message = f"Joystick button {button} pressed"
                    if button == 0:  # Assuming button 0 is the right trigger
                        self.running = False
                elif event.type == sdl2.SDL_QUIT:
                    self.running = False
                    
            # Update the window
            sdl2.ext.fill(self.window.get_surface(), sdl2.ext.Color(34, 0, 33))
            greeting = self.font.render("Press any key...", color=sdl2.ext.Color(255, 255, 255))
            sdl2.SDL_BlitSurface(greeting, None, self.window.get_surface(), None)
            if hasattr(self, 'message'):
                text_surface = self.font.render(self.message, color=sdl2.ext.Color(255, 255, 255))
                sdl2.SDL_BlitSurface(text_surface, None, self.window.get_surface(), sdl2.SDL_Rect(0, 30, 640, 480))
            if hasattr(self, 'event'):
                event_surface = self.font.render(f"Event: {self.event}", color=sdl2.ext.Color(255, 255, 255))
                sdl2.SDL_BlitSurface(event_surface, None, self.window.get_surface(), sdl2.SDL_Rect(0, 60, 640, 480))
            sdl2.SDL_UpdateWindowSurface(self.window.window)
            # Refresh the window
            
            self.window.refresh()
            sdl2.SDL_Delay(10)
            # Check for quit event
            if not self.running:
                break
        # Cleanup
        sdl2.ext.quit()

if __name__ == "__main__":
    logger = KeyLogger()
    logger.run()
                