#!/bin/bash


delay() {

    timeout 2 socat -u UNIX-CONNECT:/tmp/hypr/"$HYPRLAND_INSTANCE_SIGNATURE"/.socket2.sock - | while read -r line; do
        if [[ ${line%>>*} == "monitor"* ]]; then
            return
        fi
    done

    generate

}

generate() {
    
    unset id name horizontal vertical scale activeWorkspace

    i=0

  	while read -r k n h v s a t; do
   		id[$i]="$k"
        name[$i]="$n"
   		horizontal[$i]="$h"
   		vertical[$i]="$v"
   		scale[$i]="$s"
        activeWorkspace[$i]="$a"
        if [[ $(($t%2)) == 1 ]]; then
            temp=${vertical[$i]}
            vertical[$i]=${horizontal[$i]}
            horizontal[$i]=$temp
        fi
        ((i=i+1))
   	done < <(hyprctl monitors -j | jq -r '.[]|"\(.id) \(.name) \(.width) \(.height) \(.scale) \(.activeWorkspace.id) \(.transform)"')

#    if [[ $i > 1 ]]; then
#        displayMonitorID=true
#    else
#        displayMonitorID=false
#    fi

   	echo -n "" > $XDG_CONFIG_HOME/eww/bar.yuck

    eww close-all

    sleep 2

  	for ((i = 0; i < ${#id[@]}; i++)); do
  		scale_value=$(echo "${scale[$i]}" | bc -l)

  		new_width_float=$(echo "(${horizontal[$i]} / ${scale_value}) -10" | bc)
		new_height_float=$(echo "${vertical[$i]} / ${scale_value} * 0.03" | bc)

        new_width=$(echo "$new_width_float / 1" | bc)
        new_height=$(echo "$new_height_float / 1" | bc)

        monitorID=$(xrandr --listactivemonitors | grep +${name[$i]} | awk '{sub(/.$/,"",$1); print $1}')

        eww open bar --id bar${monitorID} --arg monitor=${monitorID} --arg width=${new_width} --arg height=25
        sleep 2

  	done



}

generate

socat -u UNIX-CONNECT:/tmp/hypr/"$HYPRLAND_INSTANCE_SIGNATURE"/.socket2.sock - | while read -r line; do
  	if [[ ${line%>>*} == "monitor"* ]]; then
        delay &
   	fi
done