#!/bin/bash

# Audio Output Management (Rofi-based)
# Dependencies: libpulse (pactl), rofi

get_volume() {
    pactl get-sink-volume @DEFAULT_SINK@ | grep -Po '[0-9]+(?=%)' | head -n 1
}

manage_sinks() {
    # Get list of sinks and their descriptions
    local sinks=$(pactl list short sinks | awk '{print $2}')
    local sink_descriptions=""
    
    while read -r line; do
        local desc=$(pactl list sinks | grep -A 20 "Name: $line" | grep "Description:" | cut -d: -f2- | xargs)
        sink_descriptions+="$desc|$line\n"
    done <<< "$sinks"

    local chosen=$(echo -e "$sink_descriptions" | column -t -s '|' | rofi -dmenu -i -p "Select Audio Output: ")
    
    if [ -n "$chosen" ]; then
        local sink_name=$(echo "$chosen" | awk '{print $NF}')
        pactl set-default-sink "$sink_name"
        notify-send "Audio" "Output switched to: $sink_name"
    fi
}

change_volume() {
    local action=$(echo -e "󰝝 Increase (+10%)\n󰝞 Decrease (-10%)\n󰝟 Mute/Unmute" | rofi -dmenu -p "Volume: $(get_volume)%")
    
    case $action in
        *"Increase"*) pactl set-sink-volume @DEFAULT_SINK@ +10% ;;
        *"Decrease"*) pactl set-sink-volume @DEFAULT_SINK@ -10% ;;
        *"Mute"*) pactl set-sink-mute @DEFAULT_SINK@ toggle ;;
    esac
}

# Main Menu
chosen=$(echo -e "󰓃 Switch Output\n󰕾 Adjust Volume\n󰍬 Manage Inputs (Microphone)" | rofi -dmenu -p "Audio Management: ")

case $chosen in
    *"Output"*) manage_sinks ;;
    *"Volume"*) change_volume ;;
    *"Inputs"*) 
        # Logic for inputs is identical to sinks, just swap 'sink' with 'source'
        sources=$(pactl list short sources | awk '{print $2}')
        chosen_source=$(echo -e "$sources" | rofi -dmenu -p "Select Input: ")
        [ -n "$chosen_source" ] && pactl set-default-source "$chosen_source"
        ;;
esac
