#!/usr/bin/env python3
"""Test that Issue #78 is fixed - Middle Mouse Click should NOT send 'C' keyboard event"""
import mcrfpy
from mcrfpy import automation
import sys

# Track events
keyboard_events = []
click_events = []

def keyboard_handler(key):
    """Track keyboard events"""
    keyboard_events.append(key)
    print(f"Keyboard event received: '{key}'")
    
def click_handler(x, y, button):
    """Track click events"""
    click_events.append((x, y, button))
    print(f"Click event received: ({x}, {y}, button={button})")

def test_middle_click_fix(runtime):
    """Test that middle click no longer sends 'C' key event"""
    print(f"\n=== Testing Issue #78 Fix (runtime: {runtime}) ===")
    
    # Simulate middle click
    print("\nSimulating middle click at (200, 200)...")
    automation.middleClick(200, 200)
    
    # Also test other clicks for comparison
    print("Simulating left click at (100, 100)...")
    automation.click(100, 100)
    
    print("Simulating right click at (300, 300)...")
    automation.rightClick(300, 300)
    
    # Wait a moment for events to process
    mcrfpy.setTimer("check_results", check_results, 500)

def check_results(runtime):
    """Check if the bug is fixed"""
    print(f"\n=== Results ===")
    print(f"Keyboard events received: {len(keyboard_events)}")
    print(f"Click events received: {len(click_events)}")
    
    # Check if 'C' was incorrectly triggered
    if 'C' in keyboard_events or 'c' in keyboard_events:
        print("\n✗ FAIL - Issue #78 still exists: Middle click triggered 'C' keyboard event!")
        print(f"Keyboard events: {keyboard_events}")
    else:
        print("\n✓ PASS - Issue #78 is FIXED: No spurious 'C' keyboard event from middle click!")
    
    # Take screenshot
    filename = f"issue78_fixed_{int(runtime)}.png"
    automation.screenshot(filename)
    print(f"\nScreenshot saved: {filename}")
    
    # Cleanup and exit
    mcrfpy.delTimer("check_results")
    sys.exit(0)

# Set up test scene
print("Setting up test scene...")
mcrfpy.createScene("issue78_test")
mcrfpy.setScene("issue78_test")
ui = mcrfpy.sceneUI("issue78_test")

# Register keyboard handler
mcrfpy.keypressScene(keyboard_handler)

# Create a clickable frame
frame = mcrfpy.Frame(50, 50, 400, 400,
                    fill_color=mcrfpy.Color(100, 150, 200),
                    outline_color=mcrfpy.Color(255, 255, 255),
                    outline=3.0)
frame.click = click_handler
ui.append(frame)

# Add label
caption = mcrfpy.Caption(mcrfpy.Vector(100, 100),
                        text="Issue #78 Test - Middle Click",
                        fill_color=mcrfpy.Color(255, 255, 255))
caption.size = 24
ui.append(caption)

# Schedule test
print("Scheduling test to run after render loop starts...")
mcrfpy.setTimer("test", test_middle_click_fix, 1000)