import ctypes, time
from PIL import ImageGrab
import win32gui

user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk: user32.SetThreadDesktop(hdesk)

hwnd = 0x2f0bf4 # PID 32572

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.06)
    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.04)

def capture(name):
    if win32gui.IsWindow(hwnd):
        rect = win32gui.GetWindowRect(hwnd)
        if rect[2] > rect[0] and rect[3] > rect[1]:
            img = ImageGrab.grab(bbox=rect, all_screens=True)
            img.save(rf"c:\Projects\JX\logs\{name}")
            print(f"Captured {name}")

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

# Step 1: Send VK_DOWN to move from "Máy chủ đã vào" (Row 1) to "Võ Công Truyền Kỳ" (Row 2)
print("Step 1: VK_DOWN to select Võ Công Truyền Kỳ...")
send_key(0x28) # VK_DOWN
time.sleep(0.6)
capture("p32572_step1_down.png")

# Step 2: Double click "Trọn Vẹn Chữ Tình" on right pane
print("Step 2: Double click 'Trọn Vẹn Chữ Tình' (610, 209)...")
click(610, 209)
time.sleep(0.3)
dblclick(610, 209)
time.sleep(0.5)

# Step 3: Click "Xác định" bottom left
print("Step 3: Click 'Xác định' (260, 503)...")
click(260, 503)
time.sleep(0.1)
send_key(0x0D) # VK_RETURN
time.sleep(2.2)
capture("p32572_step2_login_box.png")

# Step 4: Fill credentials
print("Step 4: Fill username 'nguvansi'...")
click(464, 302)
time.sleep(0.1)
for _ in range(30): send_key(0x08)
time.sleep(0.1)
for c in "nguvansi": send_char(c)
time.sleep(0.2)

print("Step 4b: Fill password 'Ngu123@@'...")
send_key(0x09) # VK_TAB
time.sleep(0.1)
for _ in range(30): send_key(0x08)
time.sleep(0.1)
for c in "Ngu123@@": send_char(c)
time.sleep(0.2)

# Step 5: Submit
print("Step 5: Submit login...")
send_key(0x0D) # VK_RETURN
time.sleep(4.0)
capture("p32572_step3_final.png")

with open(r"c:\Projects\JX\logs\p32572_step_status.txt", "w") as f:
    f.write("DONE\n")
