import time
import os
import ctypes
import winreg
from ctypes import wintypes as w

SPI_GETDESKWALLPAPER = 0x0073
dll = ctypes.WinDLL('user32')
dll.SystemParametersInfoW.argtypes = w.UINT,w.UINT,w.LPVOID,w.UINT
dll.SystemParametersInfoW.restype = w.BOOL

path = ctypes.create_unicode_buffer(260)
result = dll.SystemParametersInfoW(SPI_GETDESKWALLPAPER, ctypes.sizeof(path), path, 0)

print("Original wallpaper: ", path.value)

DEFAULT_WALLPAPER_PATH = path.value
WHITE_WALLPAPER_PATH = r"C:\Users\grego\Pictures\white wallpaper.jpg"


def set_wallpaper(image_path):
    """Change the desktop wallpaper."""
    ctypes.windll.user32.SystemParametersInfoW(20, 0, image_path, 0)


class WebcamDetect:
    REG_KEY = winreg.HKEY_CURRENT_USER
    WEBCAM_REG_SUBKEY = r"SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\webcam"
    WEBCAM_TIMESTAMP_VALUE_NAME = "LastUsedTimeStop"

    def __init__(self):
        pass

    def get_active_apps(self):
        """Returns a list of apps that are currently using the webcam."""
        def get_subkey_timestamp(subkey) -> int:
            """Returns the timestamp of the subkey."""
            try:
                value, _ = winreg.QueryValueEx(subkey, WebcamDetect.WEBCAM_TIMESTAMP_VALUE_NAME)
                return value
            except OSError:
                return None

        active_apps = []
        try:
            key = winreg.OpenKey(WebcamDetect.REG_KEY, WebcamDetect.WEBCAM_REG_SUBKEY)
            subkey_count, _, _ = winreg.QueryInfoKey(key)

            for idx in range(subkey_count):
                subkey_name = winreg.EnumKey(key, idx)
                subkey_path = f"{WebcamDetect.WEBCAM_REG_SUBKEY}\\{subkey_name}"
                subkey = winreg.OpenKey(WebcamDetect.REG_KEY, subkey_path)

                if subkey_name == "NonPackaged":
                    np_subkey_count, _, _ = winreg.QueryInfoKey(subkey)
                    for np_idx in range(np_subkey_count):
                        np_subkey_name = winreg.EnumKey(subkey, np_idx)
                        np_subkey_path = f"{WebcamDetect.WEBCAM_REG_SUBKEY}\\NonPackaged\\{np_subkey_name}"
                        np_subkey = winreg.OpenKey(WebcamDetect.REG_KEY, np_subkey_path)
                        if get_subkey_timestamp(np_subkey) == 0:
                            active_apps.append(np_subkey_name)
                        winreg.CloseKey(np_subkey)
                else:
                    if get_subkey_timestamp(subkey) == 0:
                        active_apps.append(subkey_name)

                winreg.CloseKey(subkey)
            winreg.CloseKey(key)
        except OSError as e:
            print(f"Error accessing registry: {e}")
        return active_apps

    def is_active(self):
        """Returns True if the webcam is active, False otherwise."""
        return len(self.get_active_apps()) > 0


if __name__ == "__main__":
    print("Starting webcam monitor...")
    detector = WebcamDetect()
    webcam_was_active = False

    while True:
        try:
            if detector.is_active():
                if not webcam_was_active:
                    print("Webcam activated. Changing wallpaper to white.")
                    set_wallpaper(WHITE_WALLPAPER_PATH)
                    webcam_was_active = True
            else:
                if webcam_was_active:
                    print("Webcam deactivated. Restoring default wallpaper.")
                    set_wallpaper(DEFAULT_WALLPAPER_PATH)
                    webcam_was_active = False
        except Exception as e:
            print(f"An error occurred: {e}")

        time.sleep(1)
