# Composer completion

_composer()
{
    local cur prev words cword
    _init_completion || return

    local special i
    for (( i=0; i < ${#words[@]}-1; i++ )); do
        if [[ ${words[i]} == @(require) ]]; then
            special=${words[i]}
        fi
    done

    local cache=$HOME/.composer-completion
    if [[ -n $special ]]; then
        local packages=$cache/packages.list
        if [ ! -f $packages -o $( which composer ) -nt $packages ]; then
            # checking existance of the packages list
	        mkdir -p $cache
            composer show -a | grep -v '^No composer' >$packages
        fi
        if [[ $prev != $special ]]; then
            # assume $prev is a package name
            if [[ $( cat $packages | grep "^$prev" | wc -l ) -gt 0 ]]; then
                local versions=$cache/packages/$prev/versions
                if [ ! -f $versions -o $packages -nt $versions ]; then
                    # checking cache existance
                    mkdir -p $( dirname $versions )
                    composer show $prev | \
                        sed -r -e 's/\x1b\[[0-9]+m//g' | grep ^versions | \
                        sed -r -e 's/^versions : //' -e 's/, /\n/g' >$versions
                fi
                COMPREPLY=( $( cat $versions | grep "^$cur" | sort -u ) )
            fi
        fi
        if [[ -z $COMPREPLY ]]; then
            # if $prev was not a package
            COMPREPLY=( $( cat $packages | grep "^$cur" | sort -u ) )
        fi
        return 0
    fi

    if [[ "$cur" == -* ]]; then
        COMPREPLY=( $( compgen -W '-h -q -v -V -n -d \
            --help --quiet --verbose --version --ansi --no-ansi \
            --no-interaction --profile --working-dir' -- "$cur" ) )
    else
        COMPREPLY=( $( compgen -W 'about archive config create-project \
            depends diagnose dumpautoload \
            help init install list require search \
            selfupdate show status update validate' -- "$cur" ) )
    fi

    return 0
} &&
complete -F _composer composer