import pygetwindow as gw
import pyautogui
import time
import logging
import threading
from tkinter import Tk, Label, StringVar
from screeninfo import get_monitors

import win32gui
import win32api
import win32con

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def send_click(hwnd, x, y):
    """
    Sends a click event to the specified window handle at the given coordinates.
    """
    lParam = win32api.MAKELONG(int(x), int(y))
    win32api.PostMessage(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
    time.sleep(0.01)
    win32api.PostMessage(hwnd, win32con.WM_LBUTTONUP, None, lParam)

def click_windows(title, excluded_apps, click_count, delay_between_clicks, loop_delay, update_clicks_callback):
    total_clicks = 0

    while True:
        windows_to_click = [
            win for win in gw.getAllWindows()
            if title in win.title and not any(app in win.title for app in excluded_apps)
        ]

        for win in windows_to_click:
            try:
                logging.info(f"Processing window: {win.title}")

                hwnd = win._hWnd

                if win.isMinimized or not win.isActive:
                    logging.info("Window is minimized or not active, restoring and bringing to foreground.")
                    win.restore()
                    win.activate()
                    time.sleep(0.5)  # Wait a bit for the window to become active

                # Bring window to the foreground
                try:
                    win32gui.SetForegroundWindow(hwnd)
                except Exception as e:
                    logging.error(f"Failed to bring window {win.title} to foreground: {e}")
                    continue  # Skip this window if we can't bring it to the foreground

                # Get window client area size
                left, top, right, bottom = win32gui.GetClientRect(hwnd)
                width = right - left
                height = bottom - top
                click_x = width // 2
                click_y = height // 2

                for _ in range(click_count):
                    send_click(hwnd, click_x, click_y)
                    time.sleep(delay_between_clicks)
                    total_clicks += 1
                    if update_clicks_callback:
                        update_clicks_callback(total_clicks)

                logging.info(f"Finished clicking on window {win.title}")

            except Exception as e:
                logging.error(f"Could not click on window {win.title}: {e}")

        time.sleep(loop_delay)
        if update_clicks_callback:
            update_clicks_callback(total_clicks)

def start_clicking_thread(*args, **kwargs):
    threading.Thread(target=click_windows, args=args, kwargs=kwargs, daemon=True).start()

def setup_gui():
    root = Tk()
    root.title("Click Tracker")

    click_count_var = StringVar(root, value="Total Clicks: 0")
    next_click_time_var = StringVar(root, value="Next Click: N/A")

    def update_clicks(total_clicks=0):
        click_count_var.set(f"Total Clicks: {total_clicks}")

    def update_timer():
        while True:
            remaining_time = int(loop_delay - (time.time() % loop_delay))
            next_click_time_var.set(f"Next Click in: {remaining_time}s")
            time.sleep(1)

    Label(root, textvariable=click_count_var).pack()
    Label(root, textvariable=next_click_time_var).pack()

    # Define the loop delay here
    loop_delay = 600

    start_clicking_thread(
        "Roblox",
        ["Google Chrome", "Edge", "Mozilla Firefox", "Discord", "Roblox Studio"],
        click_count=5,
        delay_between_clicks=0.25,
        loop_delay=loop_delay,
        update_clicks_callback=update_clicks
    )
    threading.Thread(target=update_timer, daemon=True).start()

    root.mainloop()

if name == "main":
    setup_gui()