import os
import time
import threading
import requests
import ctypes
from PIL import Image
from pystray import Icon, MenuItem, Menu
from win10toast import ToastNotifier

# Constants
LINK_FILE = "link.txt"
WALLPAPER_FILE = "wallpaper.png"
ICON_FILE = "icon.png"
CHECK_INTERVAL = 900  # 15 minutes in seconds

toaster = ToastNotifier()

def read_link():
    if not os.path.exists(LINK_FILE):
        return None
    with open(LINK_FILE, 'r') as f:
        return f.read().strip()

def download_image(url, save_path):
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        with open(save_path, 'wb') as f:
            f.write(response.content)
        return True
    except Exception:
        return False

def set_wallpaper(image_path):
    ctypes.windll.user32.SystemParametersInfoW(20, 0, os.path.abspath(image_path), 3)

def update_wallpaper():
    url = read_link()
    if not url:
        return
    if download_image(url, WALLPAPER_FILE):
        set_wallpaper(WALLPAPER_FILE)
        toaster.show_toast("CSC Wallpaper Updater", "Wallpaper updated", duration=3, threaded=True)

def background_loop():
    while True:
        update_wallpaper()
        time.sleep(CHECK_INTERVAL)

def start_app():
    threading.Thread(target=background_loop, daemon=True).start()

def on_update_now(icon, item):
    update_wallpaper()

def on_quit(icon, item):
    icon.stop()

def create_tray_icon():
    image = Image.open(ICON_FILE)

    menu = Menu(
        MenuItem("Update Now", on_update_now),
        MenuItem("Quit", on_quit)
    )

    icon = Icon("CSC Wallpaper Updater", icon=image, menu=menu)
    return icon


if __name__ == "__main__":
    start_app()
    tray_icon = create_tray_icon()
    tray_icon.run()