#!/usr/bin/env python3
"""
Mouse Event Testing Example

This example demonstrates comprehensive mouse event support with PtyTerminal.
It runs a simple program that enables mouse tracking and reports mouse events.

The terminal emulator supports:
1. All mouse button events (left, middle, right)
2. Mouse drag events (motion with button pressed)
3. Mouse wheel scrolling (up and down)
4. Modifier keys (Shift, Ctrl, Alt/Meta)
5. Multiple mouse tracking modes (Normal, ButtonEvent, AnyEvent)
6. Focus tracking events

The program will:
1. Enable SGR mouse encoding (1006) for extended coordinate support
2. Enable button event tracking (1002) for drag support
3. Enable focus tracking (1004)
4. Display mouse events as they occur
5. Show clicks, drags, wheel events, and modifiers
"""

import time
from par_term_emu_core_rust import PtyTerminal


def test_mouse_support():
    """Test mouse event support by running a program that captures mouse events."""
    print("=== Mouse Event Support Test ===\n")

    term = PtyTerminal(80, 24)

    # Create a simple shell script that enables mouse tracking
    # and reads mouse input
    script = """
# Enable SGR mouse tracking (mode 1006)
printf '\\033[?1006h'
# Enable mouse button event tracking (mode 1002)
printf '\\033[?1002h'
# Enable focus events
printf '\\033[?1004h'

echo "Mouse tracking enabled!"
echo "Move mouse, click, drag, and scroll in the terminal."
echo "Mouse events will appear as escape sequences."
echo ""
echo "Press Ctrl+C to exit."
echo ""

# Read and display input (this will show escape sequences)
while IFS= read -r -n1 char; do
    # Display the character code
    if [ -n "$char" ]; then
        printf "Received: [%s] " "$char"
        printf "Code: %d\\n" "'$char"
    fi
done
"""

    print("Starting mouse tracking test...")
    print("This will spawn a shell that enables mouse tracking.\n")

    term.spawn("/bin/bash", args=["-c", script])

    # Give it time to start
    time.sleep(0.5)

    # Display initial output
    print("Shell output:")
    print("=" * 60)
    output = term.content()
    print(output)
    print("=" * 60)

    # Simulate some mouse events
    print("\nSimulating mouse events...\n")

    # Mouse click at position (10, 5)
    print("1. Simulating left click at (10, 5)")
    term.write_str("\x1b[<0;10;5M")  # Button down
    time.sleep(0.1)
    term.write_str("\x1b[<0;10;5m")  # Button up
    time.sleep(0.2)

    # Mouse drag from (10, 5) to (20, 5)
    print("2. Simulating drag from (10, 5) to (20, 5)")
    term.write_str("\x1b[<0;10;5M")  # Button down
    time.sleep(0.1)
    term.write_str("\x1b[<32;15;5M")  # Move with button (32 = motion flag)
    time.sleep(0.1)
    term.write_str("\x1b[<32;20;5M")  # Move with button
    time.sleep(0.1)
    term.write_str("\x1b[<0;20;5m")  # Button up
    time.sleep(0.2)

    # Scroll wheel
    print("3. Simulating scroll wheel up")
    term.write_str("\x1b[<64;15;10M")  # Scroll up
    term.write_str("\x1b[<64;15;10m")
    time.sleep(0.2)

    print("4. Simulating scroll wheel down")
    term.write_str("\x1b[<65;15;10M")  # Scroll down
    term.write_str("\x1b[<65;15;10m")
    time.sleep(0.2)

    # Mouse events with modifiers
    print("5. Simulating Shift+click at (10, 5)")
    term.write_str("\x1b[<4;10;5M")  # Shift + left button (0 + 4)
    time.sleep(0.1)
    term.write_str("\x1b[<4;10;5m")  # Release
    time.sleep(0.2)

    print("6. Simulating Ctrl+click at (15, 5)")
    term.write_str("\x1b[<16;15;5M")  # Ctrl + left button (0 + 16)
    time.sleep(0.1)
    term.write_str("\x1b[<16;15;5m")  # Release
    time.sleep(0.2)

    # Show output
    print("\nTerminal output after mouse events:")
    print("=" * 60)
    output = term.content()
    print(output)
    print("=" * 60)

    # Clean up
    print("\nSending Ctrl+C to exit...")
    term.write(b"\x03")  # Ctrl+C
    time.sleep(0.3)

    if term.is_running():
        term.kill()

    print("\nTest complete!")
    print("\nNOTE: In a real terminal emulator (like the TUI),")
    print("the mouse events would be generated by actual mouse")
    print("interactions and forwarded to the shell automatically.")


def explain_mouse_encoding():
    """Explain the mouse encoding format."""
    print("\n" + "=" * 60)
    print("Mouse Event Encoding (SGR 1006 Format)")
    print("=" * 60)
    print()
    print("Format: \\x1b[<button;x;y;M/m")
    print()
    print("Components:")
    print("  \\x1b[<    - Escape sequence prefix")
    print("  button    - Button code (with optional modifiers):")
    print("              Base buttons:")
    print("                0 = left button")
    print("                1 = middle button")
    print("                2 = right button")
    print("                32+ = motion (add 32 to button for drag)")
    print("                64 = scroll up")
    print("                65 = scroll down")
    print("              Modifiers (added to button code):")
    print("                +4 = Shift key pressed")
    print("                +8 = Meta/Alt key pressed")
    print("                +16 = Control key pressed")
    print("  x, y      - Coordinates (1-indexed)")
    print("  M         - Button press/motion")
    print("  m         - Button release")
    print()
    print("Mouse Tracking Modes:")
    print("  1000 - Normal: press and release events")
    print("  1002 - ButtonEvent: press, release, and drag (motion with button)")
    print("  1003 - AnyEvent: all mouse motion (even without button)")
    print("  1004 - Focus tracking: focus in/out events")
    print()
    print("Examples:")
    print("  \\x1b[<0;10;5M   - Left button pressed at (10, 5)")
    print("  \\x1b[<0;10;5m   - Left button released at (10, 5)")
    print("  \\x1b[<32;15;5M  - Drag with left button to (15, 5)")
    print("  \\x1b[<4;10;5M   - Shift+left click at (10, 5)")
    print("  \\x1b[<16;10;5M  - Ctrl+left click at (10, 5)")
    print("  \\x1b[<28;10;5M  - Shift+Ctrl+left click (4+16+8=28)")
    print("  \\x1b[<64;10;10M - Scroll wheel up at (10, 10)")
    print("  \\x1b[<35;10;5M  - Motion without button (AnyEvent mode)")
    print("=" * 60)


def main():
    explain_mouse_encoding()
    print()
    test_mouse_support()


if __name__ == "__main__":
    main()
