#!/usr/bin/env zsh

#set -x
unset april sbm
unset paths
unset images
unset img_set
unset monitors
unset paper_conf

monitors="$(hyprctl -j monitors | jq --compact-output --raw-output '[.[] | {"id": .id, "name": .name, "serial": .serial}]')"
monitor_count=$(jq length <<< "${monitors}")
paper_conf="${XDG_CONFIG_HOME}/hypr/hyprpaper.conf"

typeset -a paths
#april="${HOME}/images/April"
april="/home/trey/images/April/april-nightclub.png"
sbm="${HOME}/images/Seven Beats Music"
black="${HOME}/images/black.png"

if [[ ${monitor_count} -eq 1 ]]; then
    paths=(${april})
else
    if [[ "$(kanshictl status | awk -F': ' '{print $NF}')" == "home_office" ]]; then
        paths=(${sbm})
    fi
fi

if [[ -n "${paths}" ]]; then
    typeset -a images
    for pathd in "${paths[@]}"; do
        # this line is idiomatic zsh (globbing)
        #   - N:  skip dir if it is empty
        #   - .:  only add regular files
        images+=("${pathd}"/**/*(N.))
    done
    images=(${april})
#for image in ${images[@]}; do
#    print "${image}"
#done
typeset -a img_set
while [[ ${#img_set} -le ${monitor_count} ]]; do
    #set -x
    idx=$(( ${RANDOM} % ${#images} ))
        if (( img_set[(I)${images[idx]}] )); then # if image is already in img_set
            continue 
        else
            img_set+=${images[idx]}
        fi
    done
    #
    #for img in ${img_set[@]}; do
    #    print ${img}
    #done

    #set -x
    index=1
    for pic in ${img_set[@]}; do
        if (( index > monitor_count )); then
            break
        fi
        monitor="$(jq --compact-output --raw-output --argjson i $(( index - 1 )) '.[$i].name' <<< "${monitors}")"
        #if [[ "${monitor}" == eDP-1 ]]; then
        #    index=$(( index + 1 ))
        #    continue
        #fi
        #perl -i -spe '$c+=m/^\s*monitor = .*/ if !($c xor N); s/monitor = .*$/monitor = $mon/ if $c == $N' -- -N=${idx} -mon="${monitor}" "${paper_conf}" 
        #perl -i -spe '$c+=m/^\s*path = .*/ if !($c xor N); s/path = .*$/path = $img/ if $c == $N' -- -N=${idx} -img="${pic}" "${paper_conf}" 
        #perl -i -pe '$c+=m/pattern/ if !($c xor N); s/old_string/new_string/g if $c == N' yourfile

        perl -i -s -pe '$_ = "    monitor = $mon\n" if /monitor/ && ++$n == $N' -- -N="${index}" -mon="${monitor}" "${paper_conf}"
        perl -i -s -pe '$_ = "    path = $img\n" if /path/ && ++$n == $N' -- -N="${index}" -img="${pic}" "${paper_conf}"
        index=$(( index + 1 ))
    done
    #set +x
fi
