#!/bin/bash

name="$1"
filename=/tmp/"$1"

bspc_write_nodeid() {
    while true
    do
        flag=false
        for id in $(bspc query -d focused -N -n .floating.sticky.hidden)
        do
            bspc query --node $id -T | grep -q $name && { echo $id > $filename; flag=true; break; }
        done
        [[ "$flag" == "true" ]] && break
        sleep 0.1s
    done
}

hide_all_except_current(){
    for id in $(bspc query -d focused -N -n .floating.sticky.!hidden)
    do
        bspc query --node $id -T | grep -qv $name && bspc node $id --flag hidden=on
    done
}

toggle_hidden() {
    [ -e "$filename" ] || exit 1
    hide_all_except_current
    id=$(<$filename)
    bspc node $id --flag hidden -f
}

create_terminal(){
    st -c "$name" -n "$name" -e $1 &
}

set_sizes() {
    files_window_id=$(xdotool search --class "files-scratch" | head -n 1)
    if [ ! -z "$files_window_id" ]; then
        echo "found $files_window_id"
        xdo resize -w 1864 -h 982 "$files_window_id"
        xdo move -x 28 -y 70 "$files_window_id"
    fi

    # bpytop_window_id=$(xdotool search --class "bpytop-scratch" | head -n 1)
    # if [ ! -z "$bpytop_window_id" ]; then
    #     echo "found $bpytop_window_id"
    #     xdo resize -w 1100 -h 800 "$bpytop_window_id"
    #     xdo move -x 0 -y 0 "$bpytop_window_id"
    # fi
}

if ! ps -ef | grep -q "[-]c $name"
then
    bspc rule -a "$name" --one-shot state=floating sticky=on hidden=on
    case "$name" in
        "bpytop-scratch")
            create_terminal bpytop
            ;;
        "files-scratch")
            create_terminal nnn
            ;;
        "terminal-scratch")
            create_terminal $SHELL
            ;;
        "bc-scratch")
            create_terminal bc
            ;;
        *)
            exit 1
    esac
    bspc_write_nodeid
    toggle_hidden
else
    toggle_hidden
fi

set_sizes
