#!/bin/bash

set -Eeu -o pipefail

# Bluetooth script for i3status-rust
# Shows connected Bluetooth devices

BT_ICON=""

# Check if bluetoothctl is available
if ! command -v bluetoothctl >/dev/null 2>&1; then
    echo "$BT_ICON Not available"
    exit 0
fi

# Check if Bluetooth is powered on
BLUETOOTH_POWERED=$(bluetoothctl show | grep "Powered:" | awk '{print $2}')
if [ "$BLUETOOTH_POWERED" != "yes" ]; then
    echo "$BT_ICON Off"
    exit 0
fi

# Get connected devices
# Note: bluetoothctl devices Connected doesn't work as a direct command argument
# It must be piped through bluetoothctl's interactive shell
# Also need to strip ANSI escape codes from output
CONNECTED_DEVICES=$(echo "devices Connected" | bluetoothctl 2>/dev/null | sed 's/\x1b\[[0-9;]*m//g' | grep "Device " | awk '{for(i=3;i<=NF;i++) printf "%s ", $i; print ""}' | sed 's/ $//')

if [ -z "$CONNECTED_DEVICES" ]; then
    echo "$BT_ICON No devices"
else
    # Limit the display to first 2 devices to avoid cluttering the bar
    DEVICE_COUNT=$(echo "$CONNECTED_DEVICES" | wc -w)
    if [ "$DEVICE_COUNT" -le 2 ]; then
        echo "$BT_ICON $CONNECTED_DEVICES"
    else
        FIRST_TWO=$(echo "$CONNECTED_DEVICES" | cut -d' ' -f1-2)
        echo "$BT_ICON $FIRST_TWO (+$((DEVICE_COUNT - 2)))"
    fi
fi

# Handle click events (for i3status-rust custom block)
if [ "${BLOCK_BUTTON:-}" = "1" ]; then
    # Left click - show all connected devices with details
    DETAILED_DEVICES=$(echo "devices Connected" | bluetoothctl 2>/dev/null | sed 's/\x1b\[[0-9;]*m//g' | grep "Device " | while read -r line; do
        MAC=$(echo "$line" | awk '{print $2}')
        NAME=$(echo "$line" | awk '{for(i=3;i<=NF;i++) printf "%s ", $i; print ""}' | sed 's/ $//')
        echo "• $NAME ($MAC)"
    done)
    
    if [ -n "$DETAILED_DEVICES" ]; then
        notify-send "Bluetooth Devices" "$DETAILED_DEVICES" -t 5000
    else
        notify-send "Bluetooth" "No devices connected" -t 3000
    fi
elif [ "${BLOCK_BUTTON:-}" = "3" ]; then
    # Right click - open bluetooth manager
    if command -v blueman-manager >/dev/null 2>&1; then
        blueman-manager >/dev/null 2>&1 &
    elif command -v gnome-bluetooth-panel >/dev/null 2>&1; then
        gnome-bluetooth-panel >/dev/null 2>&1 &
    else
        notify-send "Bluetooth" "No Bluetooth manager found" -t 3000
    fi
fi
