
import tkinter as tk
from tkinter import Toplevel, Entry, Label, Button, messagebox
import mysql.connector
from mysql.connector import Error
import json
import threading
from playsound import playsound

SETTINGS_FILE = "widget_settings.json"

# Screenshot uploader function to run in thread
def screenshot_service(stop_event):
    import os
    import json
    import socket
    import datetime
    import pyautogui
    import requests
    import time
    import subprocess
    import platform

    # Detect OS
    IS_WINDOWS = platform.system() == "Windows"
    IS_LINUX = platform.system() == "Linux"

    print("📣 Debug: Entered screenshot_service thread")

    import os
    os.environ["DISPLAY"] = os.environ.get("DISPLAY", ":1")  # 👈 manually set to correct display
  # ✅ Usually :0 is correct for Ubuntu

    def get_device_name():
        config_file = "config.json"
        try:
            if os.path.exists(config_file):
                with open(config_file, 'r') as f:
                    config = json.load(f)
                    return config.get("device_name", socket.gethostname())
        except:
            pass
        return socket.gethostname()

    def get_active_window():
        try:
            if IS_WINDOWS:
                import pygetwindow as gw
                active_window = gw.getActiveWindow()
                return active_window.title if active_window else "Unknown"
            elif IS_LINUX:
                win_id = subprocess.check_output(["xdotool", "getactivewindow"]).strip()
                win_name = subprocess.check_output(["xdotool", "getwindowname", win_id]).strip()
                return win_name.decode("utf-8")
        except Exception as e:
            return f"Error: {str(e)}"

    print("🟢 Screenshot service running...")
    device_name = get_device_name()

    while not stop_event.is_set():
        try:
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            folder = os.path.expanduser("~/screenshots")

            if not os.path.exists(folder):
                os.makedirs(folder)

            filename = os.path.join(folder, f"screenshot_{timestamp}.png")
            print(f"📸 Taking screenshot -> {filename}")

            try:
                screenshot = pyautogui.screenshot()
                screenshot.save(filename)
                print(f"✅ Screenshot saved: {filename}")
            except Exception as e:
                print(f"❌ Screenshot failed: {e}")
                continue

            active_app = get_active_window()
            print(f"🪟 Active Window: {active_app}")

            # Upload to server
            with open(filename, 'rb') as img:
                res = requests.post(
                    "https://skylinkonline.net/audit/upload.php",
                    files={"image": img},
                    data={"app": active_app, "device": device_name},
                    timeout=15
                )
            print(f"📤 Uploaded [{timestamp}] → Status: {res.status_code} | App: {active_app}")

            # Optional cleanup
            # os.remove(filename)

        except Exception as e:
            print(f"[CRITICAL ERROR in screenshot_service] {e}")

        # Wait for 5 minutes (300 seconds)
        for _ in range(300):
            if stop_event.is_set():
                break
            time.sleep(1)

 # total 10 sec wait

class DesktopWidget:
    def __init__(self, root):
        self.root = root
        self.root.title("Desktop Widget")

        # ✅ Define the stop event before using it
        self.stop_screenshot_event = threading.Event()

        # ✅ Now safe to start the thread
        self.screenshot_thread = threading.Thread(
            target=screenshot_service,
            args=(self.stop_screenshot_event,),
            daemon=True
        )
        self.screenshot_thread.start()

        # 🔽 rest of your UI setup...
        self.window_settings = self.load_window_settings()
        self.set_window_position_top_right()
        self.root.resizable(True, True)
        self.root.bind("<Configure>", self.save_window_size)
        self.root.protocol("WM_DELETE_WINDOW", self.prevent_close)

        name_label = tk.Label(root, text="Radhakrishna Vittaldev", font=("Helvetica", 16, "bold"))
        name_label.pack(pady=15)

        self.urls = self.load_urls()
        self.url_buttons = []
        self.create_url_buttons()

        button_frame = tk.Frame(root)
        button_frame.pack(side=tk.BOTTOM, pady=15)

        settings_btn = tk.Button(button_frame, text="Settings", command=self.open_settings, width=12, height=2, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"))
        settings_btn.pack(side=tk.LEFT, padx=10)

        timer_btn = tk.Button(button_frame, text="Timer", command=self.open_timer, width=12, height=2, bg="#FF9800", fg="white", font=("Helvetica", 10, "bold"))
        timer_btn.pack(side=tk.LEFT, padx=10)

        account_settings_btn = tk.Button(button_frame, text="Login", command=self.open_account_settings, width=15, height=2, bg="#2196F3", fg="white", font=("Helvetica", 10, "bold"))
        account_settings_btn.pack(side=tk.LEFT, padx=10)

        exit_btn = tk.Button(button_frame, text="Exit", command=self.exit_app, width=12, height=2, bg="#F44336", fg="white", font=("Helvetica", 10, "bold"))
        exit_btn.pack(side=tk.RIGHT, padx=10)

        def load_window_settings(self):
            import json
        try:
            with open(SETTINGS_FILE, "r") as f:
                settings = json.load(f)
                return settings.get("window", {})
        except Exception:
            return {}


        # Start screenshot service in background thread
        self.stop_screenshot_event = threading.Event()
        self.screenshot_thread = threading.Thread(target=screenshot_service, args=(self.stop_screenshot_event,), daemon=True)
        self.screenshot_thread.start()

    # ... (Include all your other methods here, exactly as in your original class)
    # For brevity, I'm not copying all the unchanged methods here

    def prevent_close(self):
        self.root.withdraw()
        threading.Timer(300, self.reopen_app).start()

    def reopen_app(self):
        self.root.deiconify()

    def exit_app(self):
        # Stop the screenshot thread before exiting
        self.stop_screenshot_event.set()
        self.root.destroy()

    # Add load_urls, save_urls, set_window_position_top_right, create_url_buttons, etc. from your original code here

if __name__ == "__main__":
    root = tk.Tk()
    app = DesktopWidget(root)
    root.mainloop()
