#!/bin/bash
source $HOME/.config/sway/bin/sway_helpers
SINK=$(pactl info | grep "Default Sink" | cut -d ' ' -f 3)
ICON_PATH=$HOME/.local/share/icons/Tela-circle-dark/16/actions
NOTIFY_APP="dunstify -a volume -h string:x-dunst-stack-tag:volume"
APP="pavucontrol"
SOUND=$HOME/.config/sway/bin/audio-volume-change.oga

# echo -e '\u25cf'
VOL1="●"
# echo -e '\u25cc'
VOL2="◌"

function getProgressString() {
  ITEMS="$1" # The total number of items(the width of the bar)
  FILLED_ITEM="$2" # The look of a filled item
  NOT_FILLED_ITEM="$3" # The look of a not filled item
  STATUS="$4" # The current progress status in percent

  # calculate how many items need to be filled and not filled
  FILLED_ITEMS=$(echo "((${ITEMS} * ${STATUS})/100 + 0.5) / 1" | bc)
  NOT_FILLED_ITEMS=$(echo "$ITEMS - $FILLED_ITEMS" | bc)

  # Assemble the bar string
  msg=$(printf "%${FILLED_ITEMS}s" | sed "s| |${FILLED_ITEM}|g")
  msg=${msg}$(printf "%${NOT_FILLED_ITEMS}s" | sed "s| |${NOT_FILLED_ITEM}|g")
  echo "$msg"
}

function notify() {
  VOLUME=$(pactl list sinks | grep "Name: $SINK" -A 8 | grep -oE '[0-9]*%' | head -n 1 | sed 's/%//')
  MUTE=$(pactl list sinks | grep "Name: $SINK" -A 8 | grep 'Mute:' | cut -d " " -f 2)

  echo $MUTE

  ICON=""
  TITLE=""
  if [ "$MUTE" = "yes" ]; then
    ICON=$ICON_PATH/audio-volume-muted.svg
    TITLE="${VOLUME}%"
  elif [ $VOLUME -le 33 ]; then
    ICON=$ICON_PATH/audio-volume-low.svg
    TITLE="${VOLUME}%"
  elif [ $VOLUME -le 67 ]; then
    ICON=$ICON_PATH/audio-volume-medium.svg
    TITLE="${VOLUME}%"
  else
    ICON=$ICON_PATH/audio-volume-high.svg
    TITLE="${VOLUME}%"
  fi
  # $NOTIFY_APP -i $ICON -a "Volume" "$TEXT"
  $NOTIFY_APP -i $ICON "$TITLE" "$(getProgressString 10 "$VOL1" "$VOL2" $VOLUME)"
}

##  helpers
function _toggle() {
  a=$1
  if [ $(pgrep $a) ]; then
    killall $a
  else
    $a &> /dev/null &
  fi
}

## main
if [ -z "$SINK" ]; then
  _log VOLUME ERROR args: $*
  exit 1
fi

case $1 in
  d*)
    pactl set-sink-volume $SINK -5%
    paplay $SOUND &
    notify
    ;;
  i*)
    VOLUME=$(pactl list sinks | grep "Name: $SINK" -A 8 | grep -oE '[0-9]*%' | head -n 1 | sed 's/%//')
    INC=$((100 - $VOLUME))
    if [ $INC -gt 5 ]; then
      INC=5
    fi
    pactl set-sink-volume $SINK +${INC}%
    paplay $SOUND &
    notify
    ;;
  m*)
    pactl set-sink-mute $SINK toggle
    paplay $SOUND &
    notify
    ;;
  gui)
    _check_app $APP
    _toggle $APP
    ;;
  *)
    echo "invalid command: \"$1\""
    echo "arguments: [decrease|increase|mute|gui]"
    ;;
esac