#!/usr/bin/env bash

CURRENT_THEME_LINK="/home/jannick/.config/elnixy/current/theme"
WALLPAPERS_DIR="/home/jannick/.config/elnixy/wallpapers"
CURRENT_WALLPAPER_LINK="/home/jannick/.config/elnixy/current/wallpaper"

# Get current theme
if [[ -L "$CURRENT_THEME_LINK" ]]; then
    CURRENT_THEME=$(basename "$(readlink "$CURRENT_THEME_LINK")")
else
    echo "No current theme set"
    exit 1
fi

# Get all wallpapers for current theme
WALLPAPERS=($(find "$WALLPAPERS_DIR/$CURRENT_THEME" -type f \( -name "*.jpg" -o -name "*.png" \) | sort))

if [[ ${#WALLPAPERS[@]} -eq 0 ]]; then
    echo "No wallpapers found for theme $CURRENT_THEME"
    exit 1
fi

# Get current wallpaper
if [[ -L "$CURRENT_WALLPAPER_LINK" ]]; then
    CURRENT_WALLPAPER=$(readlink "$CURRENT_WALLPAPER_LINK")
else
    CURRENT_WALLPAPER="${WALLPAPERS[0]}"
fi

# Find current wallpaper index
CURRENT_INDEX=-1
for i in "${!WALLPAPERS[@]}"; do
    if [[ "${WALLPAPERS[$i]}" == "$CURRENT_WALLPAPER" ]]; then
        CURRENT_INDEX=$i
        break
    fi
done

# Get next wallpaper (cycle back to 0 if at end)
NEXT_INDEX=$(( (CURRENT_INDEX + 1) % ${#WALLPAPERS[@]} ))
NEXT_WALLPAPER="${WALLPAPERS[$NEXT_INDEX]}"

echo "Switching to wallpaper: $(basename "$NEXT_WALLPAPER")"

# Update wallpaper symlink
ln -sf "$NEXT_WALLPAPER" "$CURRENT_WALLPAPER_LINK"

# Restart hyprpaper
pkill hyprpaper 2>/dev/null || true
sleep 0.2
nohup hyprpaper > /dev/null 2>&1 &

# Show notification
notify-send -t 2000 -a "elnixy" -u low "Wallpaper: $(basename "$NEXT_WALLPAPER")"