#!/usr/bin/env zsh

function get-titles-for-monitors {
    jq -c --null-input \
        --argjson 'monitors' "$(hyprctl -j monitors)" \
        --argjson 'workspaces' "$(hyprctl -j workspaces)" \
        '[$monitors.[].activeWorkspace.id as $active |
          $workspaces.[] | select(.id | IN($active))] |
         map({(.monitor): (if .lastwindowtitle == "" then "hyprland" else .lastwindowtitle end)}) | add'
}

function handle {
    case "${1}" in
        activewindow\>\>*|openwindow*|closewindow*)
            get-titles-for-monitors
            ;;
    esac
}

get-titles-for-monitors
socat -U - "unix-connect:/tmp/hypr/${HYPRLAND_INSTANCE_SIGNATURE}/.socket2.sock" |
    while read line; do
        handle "${line}"
    done