# import tkinter as tk
# from tkinter import messagebox
# import json
# import threading
# import os
# import datetime
# import pyautogui
# import requests
# import platform
# import socket
# import subprocess
# import time
# import sys
# os.environ['DISPLAY'] = ':0'
# os.environ['XAUTHORITY'] = '/run/user/1000/gdm/Xauthority'
# # Log everything to a file
# # sys.stdout = open(os.path.expanduser("~/python/log.txt"), "w")
# print("🟢 Widget started and logging...")

# SETTINGS_FILE = os.path.expanduser("~/widget_settings.json")

# def screenshot_service():
#     print("🟢 Screenshot service thread started", flush=True)

#     IS_WINDOWS = platform.system() == "Windows"
#     IS_LINUX = platform.system() == "Linux"

#     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)}"

#     device_name = get_device_name()

#     while True:
#         try:
#             timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
#             folder = os.path.expanduser("/mnt/testshare/screenshots")
#             if not os.path.exists(folder):
#                 os.makedirs(folder)

#             filename = os.path.join(folder, f"screenshot_{timestamp}.png")
#             print(f"📸 Capturing screenshot → {filename}", flush=True)

#             screenshot = pyautogui.screenshot()
#             screenshot.save(filename)
#             print(f"✅ Screenshot saved to: {filename}", flush=True)

#             active_app = get_active_window()
#             print(f"🪟 Active window: {active_app}", flush=True)

#             # Upload
#             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"📤 Upload response: {res.status_code}", flush=True)

#         except Exception as e:
#             print(f"❌ Error in screenshot_service: {e}", flush=True)

#         time.sleep(10000)  # Wait 1 minute for testing (change to 300 for 5 mins)

# class DesktopWidget:
#     def __init__(self, root):
#         self.root = root
#         self.root.title("Desktop Widget")

#         # Start background thread for screenshot
#         self.screenshot_thread = threading.Thread(target=screenshot_service, daemon=True)
#         self.screenshot_thread.start()

#         # UI Elements
#         name_label = tk.Label(root, text="Nellai Saravanan", font=("Helvetica", 16, "bold"))
#         name_label.pack(pady=15)

#         exit_btn = tk.Button(root, text="Exit", command=self.exit_app,
#                              width=12, height=2, bg="#F44336", fg="white", font=("Helvetica", 10, "bold"))
#         exit_btn.pack(pady=10)

#     def exit_app(self):
#         self.root.destroy()

# if __name__ == "__main__":
#     print("🚀 Starting main app...", flush=True)
#     root = tk.Tk()
#     app = DesktopWidget(root)
#     root.mainloop()

import tkinter as tk
from tkinter import ttk, messagebox
from PIL import Image, ImageTk, ImageGrab
import mysql.connector
import threading
import datetime
import pyautogui
import requests
import platform
import socket
import subprocess
import time
import os
import getpass

# --- Screenshot Service ---
def screenshot_service():
    IS_WINDOWS = platform.system() == "Windows"
    IS_LINUX = platform.system() == "Linux"

    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:
            return "Unknown"

    device_name = socket.gethostname()

    while True:
        try:
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            folder = os.path.expanduser("/mnt/testshare/screenshots")
            os.makedirs(folder, exist_ok=True)
            filename = os.path.join(folder, f"screenshot_{timestamp}.png")
            screenshot = pyautogui.screenshot()
            screenshot.save(filename)
            active_app = get_active_window()
            with open(filename, 'rb') as img:
                requests.post(
                    "https://skylinkonline.net/audit/upload.php",
                    files={"image": img},
                    data={"app": active_app, "device": device_name},
                    timeout=15
                )
        except Exception as e:
            print(f"Screenshot error: {e}")
        time.sleep(60)

# --- MySQL Authentication ---
def authenticate_user(username, password):
    try:
        conn = mysql.connector.connect(
            host="dbaas-db-1602524-do-user-4209794-0.b.db.ondigitalocean.com",
            port=25060,
            user="kirupa",
            password="revathyks@1982",
            database="skyline_track",
            ssl_disabled=False,
            ssl_verify_cert=False
        )
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM employee WHERE email=%s AND password=%s", (username, password))
        result = cursor.fetchone()
        conn.close()
        return result is not None
    except mysql.connector.Error as err:
        print(f"Database error: {err}")
        return False

# --- Main App ---
class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Akash")
        self.state('zoomed')  # Full screen
        self.resizable(True, True)

        self.login_frame = LoginFrame(self)
        self.dashboard_frame = DashboardFrame(self)

        self.login_frame.pack(fill='both', expand=True)

    def show_dashboard(self):
        self.login_frame.pack_forget()
        self.dashboard_frame.pack(fill='both', expand=True)
        self.dashboard_frame.start_background_thread()

# --- Login Frame ---
class LoginFrame(tk.Frame):
    def __init__(self, master):
        super().__init__(master)

        bg_img = Image.open("login.jpg")
        self.bg = ImageTk.PhotoImage(bg_img.resize((master.winfo_screenwidth(), master.winfo_screenheight())))
        bg_label = tk.Label(self, image=self.bg)
        bg_label.place(x=0, y=0, relwidth=1, relheight=1)

        panel = tk.Frame(self, bg='white', bd=2, relief="ridge")
        panel.place(relx=0.5, rely=0.85, anchor='s', width=500, height=250)  # Bottom center

        label_font = ("Helvetica", 12, "bold")
        entry_font = ("Helvetica", 12)
        button_font = ("Helvetica", 12, "bold")

       # -- Title (Just styled text, not a label box style)
        tk.Label(panel, text="Akash", font=("Trebuchet MS", 20, "bold"), fg="#0a84ff", bg="white").pack(pady=(10, 0))

        tk.Label(panel, text="Username:", bg="white", font=label_font).pack(pady=(10, 5))
        self.username_entry = ttk.Entry(panel, font=entry_font, width=30)
        self.username_entry.pack(pady=5)

        tk.Label(panel, text="Password:", bg="white", font=label_font).pack(pady=(10, 5))
        self.password_entry = ttk.Entry(panel, show="*", font=entry_font, width=30)
        self.password_entry.pack(pady=5)

        ttk.Button(panel, text="Login", command=self.login).pack(pady=10)

    def login(self):
        username = self.username_entry.get()
        password = self.password_entry.get()
        if username and password:
            if authenticate_user(username, password):
                self.master.show_dashboard()
            else:
                messagebox.showerror("Error", "Invalid credentials")

# --- Dashboard Frame ---
class DashboardFrame(tk.Frame):
    def __init__(self, master):
        super().__init__(master)

        bg_img = Image.open("dashboard.jpg")
        bg_img = bg_img.resize((master.winfo_screenwidth(), master.winfo_screenheight()))
        self.bg_photo = ImageTk.PhotoImage(bg_img)
        bg_label = tk.Label(self, image=self.bg_photo)
        bg_label.place(x=0, y=0, relwidth=1, relheight=1)

        self.message_label = tk.Label(self, text="Welcome to Dashboard!", font=("Helvetica", 20, "bold"), bg="#ffffff")
        self.message_label.place(relx=0.5, rely=0.2, anchor='center')

        self.thread = None

    def start_background_thread(self):
        if self.thread is None or not self.thread.is_alive():
            self.thread = threading.Thread(target=screenshot_service, daemon=True)
            self.thread.start()

# --- Run App ---
if __name__ == "__main__":
    app = App()
    app.mainloop()
    
