#!/bin/zsh
set -e

typeset -a playing
typeset -a paused
typeset -a all

process() {
    local state=$1
    shift
    local pl

    if (( ${#${(P)state}} > 1))
    then
        pl=$(rofi -dmenu<<<${(FP)state})
    else
        pl=${(FP)state}
    fi
    [[ -n $pl ]] && playerctl -p $pl $@
}

while read player ps
do
    all+=$player
    case $ps in
        Playing) playing+=$player ;;
        Paused) paused+=$player ;;
    esac
done < <(playerctl -a status --format '{{playerName}} {{status}}')

case $1 in
    toggle)
        if (( ${#playing} ))
        then
            xargs -n1 playerctl pause -p <<<${playing}
        else
            process paused play
        fi
        ;;
    next)
        process playing next
        ;;
    prev)
        process playing previous
        ;;
    open)
        shift
        process all open "$@"
esac
