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

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

# pod(){
#    # Most portable way to get the current shell name.
#    case "$(basename $(readlink /proc/$$/exe))" in
#       bash)
#          local dir=$(dirname $BASH_SOURCE)
#          perl $dir/pod.pl "$@"
#       ;;
#       zsh)
#          local dir=$(dirname ${(%):-%x})
#          perl $dir/pod.pl "$@"
#       ;;
#       *)
#          echo
#          echo "pod(): Not sure how to handle the shell: $0"
#          echo
#       ;;
#    esac
# }

_tab__pod(){
   if [ ! -e "$MY_POD_CACHE" ]; then
      _tab__pod_make_cache
   fi

   local prev="${COMP_WORDS[COMP_CWORD-1]}"
   local cur="${COMP_WORDS[COMP_CWORD]}"

   # Get possible words without considering colon characters
   _get_comp_words_by_ref -n : cur prev

   local words
   local args_cnt=$(_tab__pod_count_args "$COMP_LINE")

   # Autocomplete is based on how many words were already provided:
   # pod
   # pod Mojo::JSON
   # pod Mojo::JOSN from_json
   case $args_cnt in
       1) words=$(cat $MY_POD_CACHE) ;;
       2) words=$(pod $prev --list_class_options --list_tool_options) ;;
       *) words=$(pod --list_tool_options) ;;
   esac

   COMPREPLY=( $(compgen -W "${words[@]}" -- "$cur") )

   # echo
   # echo "COMP_WORDS    = [${#COMP_WORDS[@]}] [${COMP_WORDS[*]}]"
   # echo "COMP_CWORD    = [$COMP_CWORD]"
   # echo "prev          = [$prev]"
   # echo "cur           = [$cur]"
   # echo "args_cnt      = [$args_cnt]"
   # echo "COMP_LINE     = [$COMP_LINE]"
   # echo "COMPREPLY     = [${COMPREPLY[@]}]"
   # echo

   # Remove colon containing a prefix from COMPREPLY
   __ltrim_colon_completions "$cur" "$prev"
}

_tab__pod_make_cache(){
   _tab__pod_get_modules_list  > "$MY_POD_CACHE"
   pod --list_tool_options    >> "$MY_POD_CACHE"
}

_tab__pod_get_modules_list(){
   perl -le 'print for @INC' | while
      read dir; do
         find $dir \( -type f -or -type l \) \( -name "*.pm" \) -printf "%P\n" |
         perl -lpe '
            s&^[^/]+/&& while /-/;
            s&/&::&g;
            s/\.pm$//
         ' | sort -u
      done
}

_tab__pod_count_args(){
   perl -le '
      # Detects difference between "Mojo" and "Mojo " (simple, but important to consider).
      my @a = grep { /^[^-]/ } "@ARGV" =~ /(\S+\s+)/g;
      print scalar @a;
   ' -- "$@"
}

complete -F _tab__pod pod

