#-*- mode: shell-script; tab-width: 4-*-

# xmms2 completion
# Copyright 2005 Remi Vanicat
# License: GNU GPL v2 or later

_xmms2()
{
	local cmd cur prev query i saveifs
	
	COMPREPLY=()
	cmd=${COMP_WORDS[1]}
	cur=${COMP_WORDS[COMP_CWORD]}
	prev=${COMP_WORDS[COMP_CWORD-1]}
	
	if [ $COMP_CWORD -eq 1 ]; then
		COMPREPLY=( $(compgen -W "help add addid addpls radd clear shuffle \
sort remove list play stop pause next prev seek jump move mlib status info \
current config configlist plugin_list quit help"  -- "$cur") )
		return 0
	fi
	case "$cmd" in
		mlib)
			cmd=${COMP_WORDS[2]}
			case "$cmd$COMP_CWORD" in
				*2)
					COMPREPLY=( $(compgen -W "add loadall searchadd search \
query queryadd list_playlist save_playlist load_playlist playlists_list \
import_playlist export_playlist remove_playlist addpath rehash" -- "$cur") )
					return 0
					;;
				list_playlist3|save_playlist3|load_playlist3|import_playlist3|export_playlist3|remove_playlist3)
					COMPREPLY=($(compgen -W "$(xmms2 mlib playlists_list)" \
							-- "$cur"))
					return 0
					;;
				import_playlist4)
					return 0
					;;
				addpath*)
					return 0
					;;
				search*|searchadd*)
					if [[ "$cur" == *=* ]]; then
						prev=${cur%%=*}
						prev=${prev%%\\*}
						cur=$(echo "${cur#*=}" | sed -e 's/\\//g' | sed -e "s/'/''/g")
						query="select value from Media \
							where key='$prev' and value like '$cur%' \
							group by lower(value) order by lower(value)"
						saveifs=$IFS
						IFS="
"
						COMPREPLY=( $(xmms2 mlib query "$query"|cut -c 9- ))
# | sed -e 's/ /\\ /g' | sed -e "s/'/\\\\'/g") )
						for (( i=0; ${#COMPREPLY[@]} - i; i=i+1 )); do
							COMPREPLY[i]="$(printf '%q' "${COMPREPLY[i]}")"
						done

						IFS=$saveifs
						return 0
					else
						COMPREPLY=($(compgen -W "$(xmms2 mlib query 'select distinct key from Media' | sed 's/^key = \(.*\)$/\1/')" -- "$cur" | sed 's/$/=/'))
						return 0
					fi
			esac
			;;
		config)
			if [ $COMP_CWORD -eq 2 ]; then
				COMPREPLY=($(compgen -W  "$(xmms2 configlist | sed 's/ .*//')"))
				return 0
			fi
			;;
		addpls)
			if [ $COMP_CWORD -eq 2 ]; then
				COMPREPLY=($(compgen -W  "$(xmms2 mlib playlists_list)"))
				return 0
			fi
			;;
		sort)
			if [ $COMP_CWORD -eq 2 ]; then
				COMPREPLY=($(compgen -W  "artist title duration album \
					laststarted lmod mime added url bitrate tracknr album_id \
					artist_id track_id"))
				return 0
			fi
			;;
		radd)
			return 0
			;;
	esac
	

	return 0
}

complete -F _xmms2 -o default xmms2