import sys, time, ctypes
import win32gui
from PIL import ImageGrab

sys.stdout.reconfigure(encoding='utf-8')
user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk: user32.SetThreadDesktop(hdesk)

hwnd = 0x0063003A

def make_lparam(x, y):
    return ((y & 0xFFFF) << 16) | (x & 0xFFFF)

def click(x, y):
    lp = make_lparam(x, y)
    user32.PostMessageW(hwnd, 0x0200, 0, lp)
    time.sleep(0.04)
    user32.PostMessageW(hwnd, 0x0201, 1, lp)
    time.sleep(0.08)
    user32.PostMessageW(hwnd, 0x0202, 0, lp)
    time.sleep(0.05)

def capture(name):
    rect = win32gui.GetWindowRect(hwnd)
    img = ImageGrab.grab(bbox=rect, all_screens=True)
    path = rf"c:\Projects\JX\logs\{name}.png"
    img.save(path)
    print(f"Captured: {path}")

user32.SetForegroundWindow(hwnd)
time.sleep(0.2)

# Click the green down arrow of the username combobox:
# In crop: arrow is around x=240 in crop => 240+240-3 = 477 client X?
# Wait! Let's check where the arrow is in image:
# Image X: crop starts at 240. The arrow is at crop x = 240..255.
# So image X = 480..495!
# Client X = 480..495 - 3 = 482!
# Image Y = 283. Client Y = 283 - 26 = 257!
print("Clicking dropdown arrow at (482, 257)...")
click(482, 257)
time.sleep(0.5)
capture("test_arrow_clicked")

# What if we click at (350, 257)?
print("Clicking text area at (350, 257)...")
click(350, 257)
time.sleep(0.5)
capture("test_textarea_clicked")

# What if we click at (320, 257)?
print("Clicking far left of box at (320, 257)...")
click(320, 257)
time.sleep(0.5)
capture("test_left_clicked")
