#!/bin/bash

export MY_CACHE_DIR="$HOME/.cache"
export MY_POD_CACHE="$MY_CACHE_DIR/my_pod_clases.cache"

# Build list of all perl modules.
_tab__pod_get_all_modules(){
    perl -le 'print for @INC' |
    xargs -I {} find {} -name '*.pm' -printf '%P\n' |
    sort -u |
    while read f; do
        f="${f//\//::}"
        f="${f%\.pm}"
        echo $f
    done
}

_my_clear_cache(){
    rm -frv $MY_CACHE_DIR/my_*.cache
}

_tab__pod_filter(){
    perl -lne '
        INIT {
            $cur = shift @ARGV;
            $cnt =()= $cur =~ /::/g;
            %matches;
        }
        # No match.
        next if index($_, $cur) != 0;

        # Do not show too much.
        my $index = -1;
        for my $c ( 0 .. $cnt ) {
            $index = index($_, "::", $index+1);
        }
        if ($index != -1){
            $_ = substr($_, 0, $index+2 );
        }

        $matches{$_}++;

        END {
            for ( sort keys %matches ) {

                # Check if there is a longer name and use it.
                if ( substr($_, -2 ) ne "::" ) {
                    next if $matches{ $_ . "::"};
                }

                print;
            }
        }

    ' "$1" $MY_POD_CACHE
}

_tab__pod(){
    if ! [ -e $MY_POD_CACHE ]; then
        _tab__pod_get_all_modules > $MY_POD_CACHE
    fi

    local cur prev words cword _possible
    _init_completion -n : || return

    if [[ $cur =~ ^- ]]; then                    # Option
        _possible=$(pod --tool_options)
        COMPREPLY=($(compgen -W "$_possible" -- $cur))
    elif [[ "$prev" =~ ^-+q(uery)?$ ]]; then     # --query
        return                                   # Since it can be anything.
    else
        _possible=$(_tab__pod_filter "$cur" )
        compopt -o nospace                       # No space afterwards.
        COMPREPLY=($(compgen -W "$_possible" -- $cur))
        __ltrim_colon_completions "$cur"
    fi
}

complete -F _tab__pod pod

