#!/bin/bash

ECHO=""
COLOR="#999999"

BLUETOOTHCTL=$(which bluetoothctl)

# Check if bluetoothctl exists
if [ ! -x "$BLUETOOTHCTL" ]; then
   ECHO="X"
# Check if Bluetooth is powered on
else

   if ! bluetoothctl show | grep -q "Powered: yes"; then
      ECHO="x"
   else

      # Function to get all available devices (both paired and unpaired)
      get_available_devices() {
          $BLUETOOTHCTL devices | awk '{$1=$2=""; print $0}' | xargs
      }

      # Function to get all paired devices
      get_paired_devices() {
          $BLUETOOTHCTL devices Paired | awk '{$1=$2=""; print $0}' | xargs
      }

      # Function to get connected devices
      get_connected_devices() {
          $BLUETOOTHCTL devices Connected | awk '{$1=$2=""; print $0}' | xargs
      }

      # List paired devices
      CONNECTED_DEVICES=$(get_connected_devices)

      # Count connected devices
      CONNECTED_COUNT=$(echo "$CONNECTED_DEVICES" | wc -l)

      ALL_DEVICES=""
      # If clicked, show available devices (both connected and unconnected)
      if [ "$BLOCK_BUTTON" == 1 ]; then

          AVAILABLE_DEVICES=$(get_available_devices)
          PAIRED_DEVICES=$(get_paired_devices)

          FILTER=""
          for word in $AVAILABLE_DEVICES; do
             if ! [[ " $PAIRED_DEVICES " =~ " $word " ]]; then
                FILTER+="$word "
             fi
          done
          AVAILABLE_DEVICES=$FILTER

          FILTER=""
          for word in $PAIRED_DEVICES; do
             if ! [[ " $CONNECTED_DEVICES " =~ " $word " ]]; then
                FILTER+="$word "
             fi
          done
          PAIRED_DEVICES=$FILTER

          AVAILABLE_DEVICES=$(echo "$AVAILABLE_DEVICES" | xargs)
          PAIRED_DEVICES=$(echo "$PAIRED_DEVICES" | xargs)
          CONNECTED_DEVICES=$(echo "$CONNECTED_DEVICES" | xargs)

          # all connected are paired, all paired are available

          if [ -n "$AVAILABLE_DEVICES" ]; then
             ALL_DEVICES+="<span color=\'#CCCCCC\'>$AVAILABLE_DEVICES</span> "
          fi

          if [ -n "$PAIRED_DEVICES" ]; then
             ALL_DEVICES+="<span color=\'#999999\'>$PAIRED_DEVICES</span> "
          fi

          if [ -n "$CONNECTED_DEVICES" ]; then
             ALL_DEVICES+="<span color=\'#0099cc\'>$CONNECTED_DEVICES</span> "
             COLOR="#0099cc"
          fi

          ALL_DEVICES=$(echo "$ALL_DEVICES" | xargs)
          ECHO="$ALL_DEVICES"

      # Default display (if there are no connected devices)
      else
         if [ -z "$CONNECTED_DEVICES" ]; then
            ECHO=""
         else
            # Display connected devices count
            ECHO="$CONNECTED_COUNT"
            COLOR="#0099CC"
         fi
      fi
   fi
fi


if [ -n "$ECHO" ]; then
   echo "<span color='$COLOR'>B $ECHO</span>"
else
   echo "<span color='$COLOR'>B</span>"
fi
exit 0