#!/bin/bash

# Lock file for preventing multiple instances
lockfile="/tmp/title-bar.lock"

# Check if the lock file exists and obtain the PID
if [ -e "$lockfile" ]; then
    # If the lock file exists, check if the process is still running
    lock_pid=$(cat "$lockfile")
    if ps -p "$lock_pid" >/dev/null; then
        echo "title-bar is already running. Exiting."
        exit 1
    else
        # If the process is not running, remove the stale lock file
        rm "$lockfile"
    fi
fi

# Create a new lock file with the current PID
echo "$$" >"$lockfile"

# Debug log file
DEBUG_LOG="/tmp/title-bar_debug.log"

# Debug function
debug_echo() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >>"$DEBUG_LOG"
}

debug_echo "Script execution started."

# Background image path
bg_path="/tmp/bg_${bgw}.png"

# Function to create background images
create_background_image() {
    echo -e "\e[48;2;255;165;0m" # Orange color
}

# Kill existing lemonbar instances and update script
pkill -f "lemonbar"
pkill -f "update-title"

# Get the focused window information
focused_info="$(bspc query -T --names -M)"

# Get the focused window ID
focused_id="$(bspc query -N -n focused)"

# Check if the window ID is empty
if [ "$focused_id" = "" ]; then
    echo "No focused window found."
    exit
fi

# Check if the focused window is in fullscreen mode
if bspc query -T -n "$focused_id" | grep -q '"state":"fullscreen"'; then
    echo "Focused window is in fullscreen mode. Exiting."
    rm -f "$lockfile" # Remove the lock file
    exit
fi

# Get the WM_CLASS of the focused window
focused_class="$(xprop WM_CLASS -id "$focused_id" | awk -F '"' '{print $2}')"

debug_echo "Focused Class: $focused_class"

# Exclude certain window classes
case "$focused_class" in
    "Nwg-menu" | "nwg-menu" | "Steam" | "Qmmp" | "Wrapper-1.0" | "xfce4-panel")
        debug_echo "Excluded window class: $focused_class. Exiting script."
        rm -f "$lockfile" # Remove the lock file
        exit
        ;;
esac

# Get focused window geometry
read -r x y w h < <(xwininfo -id "$focused_id" |
    awk '/Absolute upper-left X:/ { x=$4 }
       /Absolute upper-left Y:/ { y=$4 }
       /Width:/ { w=$2 }
       /Height:/ { h=$2 }
END { print x, y, w, h }')

#geoBar=$(echo "$w 13 $x $y" | awk '{print $1+4"x13+"$3"+"$4-8}')
#geoBar=$(echo "$w 13 $x $y" | awk '{print $1-7"x10+"$3+5"+"$4-4}')
geoBar=$(echo "$w 13 $x $y" | awk '{print $1+7"x10+"$3"+"$4}')

# Create background image based on window width
create_background_image

# Launch lemonbar with consistent background color
echo -e "%{c}%{I:${bg_path}:}%{l}%{I#FF000000:$HOME/.scripts/assets/corner.png:}%{r}%{I:$HOME/.scripts/assets/corner.png:}" |
lemonbar -d -p -B "#000000" -U "#FFFFFF" -F "#FFFFFF" -f "Jetbrains Mono:bold:size=10" -g "$geoBar" &
#lemonbar -d -p -B "#FFFFFF" -U "#000000" -F "#000000" -f "Jetbrains Mono:bold:size=10" -g "$geoBar" &
#lemonbar -d -p -B "$HOME/.scripts/assets/trans.png" -U "#77dd77" -F "#4e585d" -f "Terminus:size=1" -g "$geoBar" &
sleep 0.05

# Launch update-title for the focused window
~/.scripts/update-title "$focused_id" | lemonbar -d -g "$geoBar" -f "Jetbrains Mono:bold:size=6" -f "Jetbrains Mono:bold:size=6" -p | bash &

# Wait for lemonbar to start
sleep 0.1

# Adjust stacking order for the focused window
barinfos="$(xwininfo -tree -root | grep "$focused_id")"
bgid="$(echo "$barinfos" | tail -n 1 | awk '{print $1}')"
xdo below -t "$focused_id" "$bgid"
xdo above -t "$bgid" "$(echo "$barinfos" | head -n 1 | awk '{print $1}')"

debug_echo "Script execution completed."

# Function to handle updates triggered by BSPWM events
handle_bspwm_events() {
    while read -r line; do
        event_type=$(echo "$line" | jq -r '.type')

        case "$event_type" in
            focus_changed)
                focused_node=$(echo "$line" | jq -r '.node')
                ~/.scripts/update-title "$focused_node" | lemonbar -p -g "$geoBar" -f "Jetbrains Mono:size=6" -f "Jetbrains Mono:size=6" | bash &
                ;;
            node_add | node_remove | node_flag | node_geometry)
                # Handle other node-related events
                ;;
            *)
                # Handle other events as needed
                ;;
        esac
    done
}

# Subscribe to BSPWM events and pass them to the handler function
bspc subscribe | handle_bspwm_events &

# Remove the lock file when the script exits
trap 'rm -f "$lockfile"; pkill -f "title-bar"; exit 0' EXIT
