import sys
import socket
import time
from PIL import Image, ImageDraw, ImageFont

if len(sys.argv) < 2:
    print("Usage: python3 generate_image.py <IP_ADDRESS> [TEXT]")
    sys.exit(1)

IP_ADDRESS = sys.argv[1]
PORT = 4242
TEXT_TO_DRAW = sys.argv[2] if len(sys.argv) > 2 else "Hello from Python!"

WIDTH = 400
HEIGHT = 300

# Create a new image with white background (1 = White, 0 = Black)
image = Image.new('1', (WIDTH, HEIGHT), 1)
draw = ImageDraw.Draw(image)

print("Generating pattern...")

# Draw Borders
draw.rectangle([(0, 0), (WIDTH-1, HEIGHT-1)], outline=0, width=3)

# Draw Diagonal Cross
draw.line([(0, 0), (WIDTH-1, HEIGHT-1)], fill=0, width=2)
draw.line([(0, HEIGHT-1), (WIDTH-1, 0)], fill=0, width=2)

# Draw a filled box in the center
center_x = WIDTH // 2
center_y = HEIGHT // 2
box_size = 50
draw.rectangle([(center_x - box_size, center_y - box_size), 
                (center_x + box_size, center_y + box_size)], fill=0)

# Draw Text
try:
    # Try to load a nice font
    # On macOS, Arial is usually available.
    font = ImageFont.truetype("/Library/Fonts/Arial.ttf", 36)
except IOError:
    try:
        # Try Linux path
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 36)
    except IOError:
        print("Warning: Could not load custom font, using default.")
        font = ImageFont.load_default()

# Calculate text size
try:
    # Pillow >= 9.2.0
    left, top, right, bottom = draw.textbbox((0, 0), TEXT_TO_DRAW, font=font)
    text_width = right - left
    text_height = bottom - top
except AttributeError:
    # Older Pillow
    text_width, text_height = draw.textsize(TEXT_TO_DRAW, font=font)

text_x = (WIDTH - text_width) // 2
text_y = 40 # Top area

# Draw white background for text so it's readable
padding = 10
draw.rectangle([(text_x - padding, text_y - padding), 
                (text_x + text_width + padding, text_y + text_height + padding)], 
               fill=1, outline=0)

# Draw text
draw.text((text_x, text_y), TEXT_TO_DRAW, font=font, fill=0)

# Convert to bytes
# PIL tobytes for mode '1' packs 8 pixels per byte, MSB first.
buffer = image.tobytes()

print(f"Connecting to {IP_ADDRESS}:{PORT}...")

try:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((IP_ADDRESS, PORT))
        print("Connected. Sending command...")
        s.sendall(b"/image\n")
        time.sleep(0.5) # Small delay to ensure command is processed
        print(f"Sending {len(buffer)} bytes of image data...")
        s.sendall(buffer)
        time.sleep(1)
        print("Done.")
except Exception as e:
    print(f"Error: {e}")

