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
print(f"Target HWND: 0x{hwnd:X}, Valid: {win32gui.IsWindow(hwnd)}")

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 dblclick(x, y):
    lp = make_lparam(x, y)
    user32.PostMessageW(hwnd, 0x0200, 0, lp)
    time.sleep(0.03)
    user32.PostMessageW(hwnd, 0x0201, 1, lp)
    time.sleep(0.05)
    user32.PostMessageW(hwnd, 0x0202, 0, lp)
    time.sleep(0.05)
    user32.PostMessageW(hwnd, 0x0203, 1, lp)
    time.sleep(0.05)
    user32.PostMessageW(hwnd, 0x0202, 0, lp)
    time.sleep(0.05)

def send_key(vk):
    lp = (0x1C << 16) | 1
    user32.PostMessageW(hwnd, 0x0100, vk, lp)
    time.sleep(0.04)
    user32.PostMessageW(hwnd, 0x0101, vk, lp | (3 << 30))
    time.sleep(0.04)

def send_char(c):
    lp = (ord(c) << 16) | 1
    user32.PostMessageW(hwnd, 0x0102, ord(c), 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)

# Step 1: Open Login Dialog from Server Selection
print("Opening Login Dialog...")
click(610, 209)
time.sleep(0.2)
dblclick(610, 209)
time.sleep(0.3)
click(260, 503) # Xác định
time.sleep(0.1)
send_key(0x0D)
time.sleep(2.0)
capture("diag_0_opened")

# Test 1: Click at (330, 254)
print("Test 1: Click (330, 254)...")
click(330, 254)
time.sleep(0.2)
capture("diag_1_clicked_330")

# Type 'testuser'
print("Type 'testuser'...")
for c in "testuser":
    send_char(c)
time.sleep(0.3)
capture("diag_2_typed_testuser")

# Test 2: Click at (400, 254)
print("Test 2: Click (400, 254)...")
click(400, 254)
time.sleep(0.2)
for c in "123":
    send_char(c)
time.sleep(0.3)
capture("diag_3_typed_123")

# Test 3: Tab
print("Test 3: Tab...")
send_key(0x09) # VK_TAB
time.sleep(0.2)
for c in "tabtext":
    send_char(c)
time.sleep(0.3)
capture("diag_4_tab_typed")

print("Diagnosis finished.")
