#!/bin/bash

ICON_THEME="ePapirus-Dark"

declare -A occupiedWorkspaces
declare -A workspaceActiveOn
declare -A workspaces
PIDs=()
workspaces=()
A=()
image=()



# get the monitors workspaces are active on and get workspaces that exist

workspace_event() {

    unset workspaceActiveOn
	unset occupiedWorkspaces

# store the monitor id in workspaceActiveOn with the index of the active workspace

    while read -r m w; do
        workspaceActiveOn[$w]=$m
    done < <(hyprctl -j monitors | jq -r '.[]|"\(.id) \(.activeWorkspace.id)"')

# set occupiedWorkspaces with the workspace as its index true if the index exists

    while read -r i; do
        if (( $i > 0 )); then
            occupiedWorkspaces[$i]=true
        fi
    done < <(hyprctl -j workspaces | jq -r '.[]|"\(.id)"')

}



client_event() {

unset clientOnWorkspace
unset PIDs
unset classes
unset icons

    classes=()
    clientOnWorkspace=()
    images=()
    numberOnWorkspace=()
    area=()
    i=0

    while read -r p w x y c; do
        if [[ $c ]]; then

# read PIDs of all clients in consecutive order

            PIDs[$i]="$p"

# store class of process at index of its PID

            classes[$p]="$c"

# store workspace process is on at index of its PID

            clientOnWorkspace[$p]="$w"

# increment numberOnWorkspace by one to reflect amount of clients on it

            ((numberOnWorkspace[w]+=1))

# store area of the process at index of its PID

            area[$p]=$((x * y))

# get icon in a hacky way

            desktop=$(grep -l "StartupWMClass.*$c$" /usr/share/applications/*.desktop)
            if [ -z $desktop ]; then
                desktop=$(grep -Pl "Name\s*=\s*$c$" /usr/share/applications/*.desktop)
            fi
            if [ -z $desktop ]; then
                desktop=$(ls /usr/share/applications | grep -l /usr/share/applications/${c}.desktop)
            fi
            if [ -z $desktop ]; then
                process=$(ps -p ${p} -o comm=)
                desktop=$(grep -Pl "$process" /usr/share/applications/*.desktop)
            fi
            if [ -z $desktop ]; then
                desktop=$(grep -Pli "$c" /usr/share/applications/*.desktop)
            fi
            if [ -z $desktop ]; then
                continue
            fi

            image=$(awk -F'[[:space:]]*=[[:space:]]*' '/Icon[[:space:]]*=/{print $2}' $desktop)
            icons[$p]="/usr/share/icons/Papirus-Dark/128x128/apps/${image}.svg"
            ((i=$i+1))
            
        fi
    done < <(hyprctl clients -j | jq -r '.[]|"\(.pid) \(.workspace.id) \(.size[0]) \(.size[1]) \(.initialClass)"')

# store json string of all client information at the index of the clients pid

    for ((i=0; i<${#PIDs[@]}; i++)); do
        PID=${PIDs[$i]}
        clientInfos[PID]='{"onWorkspace":"'${clientOnWorkspace[$PID]}'","pid":"'${PID}'","class":"'${classes[$PID]}'","mainOn":"''","icon":"'${icons[$PID]}'"}'
    done

}


# generate the json for eww
generate() {

    unset message
    
    message='['

    for i in {1..9}; do

        message=$message''$([ $i -eq 1 ] || echo ,)'{"ID":"'$i'","occupied":"'${occupiedWorkspaces[$i]}'","activeID":"'${workspaceActiveOn[$i]}'","clients":['

        firstClient=0

        for ((j=0; j<${#PIDs[@]}; j++)); do

            PID=${PIDs[j]}
            
            if [[ $(echo ${clientInfos[$PID]} | jq '"\(.onWorkspace)"') == '"'${i}'"' ]]; then
                message=$message''$([ $firstClient -eq 0 ] || echo ,)''${clientInfos[$PID]}''
                firstClient=1
            fi
            
        done

        message=$message']}'
    done

    message="${message}]"

    echo $message
}

# setup


# generate initial widget
workspace_event
client_event
generate

socat -u UNIX-CONNECT:/tmp/hypr/"$HYPRLAND_INSTANCE_SIGNATURE"/.socket2.sock - | while read -r line; do
    case ${line%>>*} in
        "workspace")
            workspace_event
            generate
            ;;
#        "createworkspace")
#            workspace_event
#            generate
#            ;;
#        "destroyworkspace")
#            workspace_event
#            generate
#            ;;
#        "moveworkspace")
#            workspace_event
#            generate
#            ;;
        "openwindow")
            client_event
            generate
            ;;
        "closewindow")
            client_event
            generate
            ;;
        "movewindow")
            client_event
            workspace_event
            generate
            ;;
    esac
done