#!/usr/bin/python3
# import argparse
import os
import sys
import subprocess
import json


def get_window():
    print("Getting active window",flush=True)
    state = subprocess.run(["hyprctl", "activewindow", "-j"], capture_output=True, text=True)
    state = state.stdout
    try:
        state = json.loads(state)
    except json.JSONDecodeError:
        print("Error decoding JSON")
        return None
    if state is None:
        print("No active window")
        return None
    if "class" not in state:
        return None
    return state["class"]

def gromit_running():
    clients = subprocess.run(["hyprctl", "clients", "-j"], capture_output=True, text=True)
    clients = clients.stdout
    try:
        clients = json.loads(clients)
    except json.JSONDecodeError:
        print("Error decoding JSON")
        return False
    if clients is None:
        print("No clients")
        return False
    for client in clients:
        if "class" not in client:
            continue
        if client["class"] == "Gromit-mpx":
            return True
    return False
    


if __name__ == "__main__":
    if get_window() == "Gromit-mpx":
        print("Gromit is already running")
        os.system("hyprctl dispatch togglespecialworkspace gromit")
        os.system("gromit-mpx -t")
        os.system("hyprctl keyword unbind , mouse_left")
        os.system("hyprctl keyword unbind , mouse_right")
        print("Rebinding mouse buttons")
        os.system("hyprctl keyword bind , mouse_left, exec, 'ydotool key 56:1 105:1 105:0 56:0'")
        os.system("hyprctl keyword bind , mouse_right, exec, 'ydotool key 56:1 106:1 106:0 56:0'")
        # Set dim special to default
        os.system("hyprctl keyword decoration:dim_special 0.5")
        os.system("hyprctl keyword decoration:blur:special 1")

    else:
        print("Gromit is not running",flush=True)
        # Check if gromit-mpx is running
        if gromit_running():
            os.system("gromit-mpx -t")
        
        # Disable dim special
        os.system("hyprctl keyword decoration:dim_special 0")
        os.system("hyprctl keyword decoration:blur:special 0")
        os.system("hyprctl dispatch togglespecialworkspace gromit")
        os.system("hyprctl keyword unbind , mouse_left")
        os.system("hyprctl keyword unbind , mouse_right")
        os.system("hyprctl keyword bind , mouse_left, exec, 'gromit-mpx --undo'")
        os.system("hyprctl keyword bind , mouse_right, exec, 'gromit-mpx --redo'")
        

    