#!/usr/bin/env python3

import dbus
import dbus.mainloop.glib
import os
from gi.repository import GLib

# Define the paths to the PNG icons
ICON_PATHS = {
    "nvidia": "/home/teraflops/Icons/nvidia-icon.svg",
    "integrated": "/home/teraflops/Icons/amd.png",
}

# Function to interpret the numerical status into a clearer message
def interpret_gpu_status(status):
    if status == 0:
        return "nvidia"
    elif status == 1:
        return "integrated"
    else:
        return None  # Ignore "switching mode" and other unknown statuses

# Function to send the signal using `os.system()`
def send_signal_to_waybar():
    try:
        print("Sending RTMIN+3 signal to Waybar using os.system")  # Debug message
        os.system("/usr/bin/pkill -RTMIN+3 waybar")
    except Exception as e:
        print(f"Error sending the signal with os.system: {e}")

# Function to write the icon path as a shell script in /tmp/gpu
def write_gpu_icon_script(status_message):
    try:
        icon_path = ICON_PATHS.get(status_message)
        if icon_path:
            print(f"Writing to /tmp/gpu: #!/bin/sh\necho \"{icon_path}\"")  # Debug message
            with open("/tmp/gpu.sh", "w") as file:
                file.write(f"#!/bin/sh\necho \"{icon_path}\"\n")
            # Make the script executable
            os.chmod("/tmp/gpu.sh", 0o755)
            print(f"GPU script saved in /tmp/gpu: #!/bin/sh\necho \"{icon_path}\"")
        else:
            print(f"No icon found for the status: {status_message}")
    except Exception as e:
        print(f"Error writing the script in /tmp/gpu: {e}")

# Callback for `NotifyGfxStatus`
def on_notify_gfx_status(status):
    print(f"`on_notify_gfx_status` callback invoked with status: {status}")  # Debug
    status_message = interpret_gpu_status(status)

    # If the status is not "nvidia" or "integrated", ignore it
    if status_message:
        print(f"GPU Status changed: {status_message}")

        # Save the shell script with the icon path in /tmp/gpu
        write_gpu_icon_script(status_message)

        # Send the signal to Waybar using os.system
        send_signal_to_waybar()
    else:
        print("Intermediate status detected, no action will be taken.")

# Callback for `NotifyGfx`
def on_notify_gfx(vendor):
    print(f"`on_notify_gfx` callback invoked with vendor: {vendor}")

# Callback for `NotifyAction`
def on_notify_action(action):
    print(f"`on_notify_action` callback invoked with action: {action}")

# Initialize the D-Bus loop
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

# Connect to the system bus and get the object
bus = dbus.SystemBus()
proxy = bus.get_object("org.supergfxctl.Daemon", "/org/supergfxctl/Gfx")

# Subscribe to the `NotifyGfxStatus`, `NotifyGfx`, and `NotifyAction` signals
bus.add_signal_receiver(on_notify_gfx_status,
                        dbus_interface="org.supergfxctl.Daemon",
                        signal_name="NotifyGfxStatus")

bus.add_signal_receiver(on_notify_gfx,
                        dbus_interface="org.supergfxctl.Daemon",
                        signal_name="NotifyGfx")

bus.add_signal_receiver(on_notify_action,
                        dbus_interface="org.supergfxctl.Daemon",
                        signal_name="NotifyAction")

print("Monitoring GPU signals...")

# Start the main loop
loop = GLib.MainLoop()
loop.run()

