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

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

hwnd = 0x60b66 # PID 29956 (MeCuaCacCon / nguvansi3)
if not win32gui.IsWindow(hwnd):
    print(f"ERROR: HWND {hex(hwnd)} is not valid!")
    sys.exit(1)

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

WM_MOUSEMOVE = 0x0200
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
WM_LBUTTONDBLCLK = 0x0203
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101
WM_CHAR = 0x0102
VK_BACK = 0x08
VK_TAB = 0x09
VK_RETURN = 0x0D

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

def send_char(c):
    lp = (ord(c) << 16) | 1
    user32.PostMessageW(hwnd, WM_CHAR, ord(c), lp)
    time.sleep(0.04)

def click_client(x, y):
    lp = make_lparam(x, y)
    user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp)
    time.sleep(0.04)
    user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lp)
    time.sleep(0.08)
    user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
    time.sleep(0.05)

def dblclick_client(x, y):
    lp = make_lparam(x, y)
    user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp)
    time.sleep(0.03)
    user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lp)
    time.sleep(0.05)
    user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
    time.sleep(0.08)
    user32.PostMessageW(hwnd, WM_LBUTTONDBLCLK, 1, lp)
    time.sleep(0.05)
    user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
    time.sleep(0.05)

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

# Step 1: Select "Trọn Vẹn Chữ Tình" on the right pane
print("Clicking 'Trọn Vẹn Chữ Tình' at (550, 195)...")
click_client(550, 195)
time.sleep(0.3)
dblclick_client(550, 195)
time.sleep(0.5)

# Step 2: Click "Xác định" bottom-left of dialog
print("Clicking 'Xác định' at (260, 503)...")
click_client(260, 503)
send_key(VK_RETURN)
time.sleep(2.0)

capture("step_after_server.png")

# Step 3: Enter credentials
print("Filling username: nguvansi3...")
click_client(464, 302)
time.sleep(0.1)
for _ in range(30):
    send_key(VK_BACK)
time.sleep(0.1)
for c in "nguvansi3":
    send_char(c)
time.sleep(0.2)

print("Filling password: Ngu123@@...")
send_key(VK_TAB)
time.sleep(0.1)
for _ in range(30):
    send_key(VK_BACK)
time.sleep(0.1)
for c in "Ngu123@@":
    send_char(c)
time.sleep(0.2)

print("Submitting login credentials...")
send_key(VK_RETURN)
time.sleep(3.5)

capture("step_after_login.png")

with open("c:/Projects/JX/logs/step_done.txt", "w") as f:
    f.write("OK\n")
print("Login step completed successfully.")
