#!/usr/bin/env bash

# Variable to store the last focused window address
last_focused_window=""
current_window=""

# PID of the swww-daemon process
swww_pid=""

# Get the PID of the swww-daemon process
get_swww_pid() {
    swww_pid=$(pgrep -f swww-daemon)
}

function handle {
    if [[ ${1:0:14} == "activewindowv2" ]]; then
        new_window="${1:16}"

        # Update window tracking
        last_focused_window="${current_window}"
        current_window="${new_window}"

        get_swww_pid
        
        if [[ ! -n "$swww_pid" ]]; then
            return 1
        fi
        
        # XXX: please review
        if [[ $(cat "$HOME/.config/hypr/conditions/autofreeze_swww") -eq 0 ]]; then
            kill -CONT "$swww_pid" 2>/dev/null
            return 0
        fi

        # Process for unfreezing if there is no active window
        if  [[ $(hyprctl activeworkspace -j | jq '.id') = 9 ]] || [[ ! -n "$current_window" ]]; then
            echo "Unfreezing swww-daemon (PID: $swww_pid)"
            kill -CONT "$swww_pid" 2>/dev/null
        else
            echo "Freezing swww-daemon (PID: $swww_pid)"
            kill -STOP "$swww_pid" 2>/dev/null
            return 0
        fi

    fi
}

# Listen for events
socat - "UNIX-CONNECT:$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock" | while read -r line; do handle "$line"; done

