#!/usr/bin/env bash

_oo_completion() 
{ 
    printf "\n"
    c2contxt=(${COMP_LINE:0:$COMP_POINT})
    cur="${c2contxt[$COMP_CWORD]}"
    if [ -z "$cur" ]; then
        cur="--"
    fi

    info.log "line til cursor   : ${COMP_LINE:0:$COMP_POINT}" # line til cursor
    info.log "line from cursor  : ${COMP_LINE:$COMP_POINT}"   # line from cursor
    info.log "whole line        : ${COMP_LINE}"               # whole line
    info.log "cursor pos in line: ${COMP_POINT}"              # cursor pos in line
    info.log "index of the word : ${COMP_CWORD}"               # index of the word
    info.log "current completion: $cur"                       # current completion word


    $OOSH_DIR/ng/c2 completion.discover "${COMP_CWORD}" "$cur" ${COMP_WORDS[*]} - 
    COMPREPLY=( $( cat $CONFIG_PATH/completion.result.txt ) )
    # echo "${YELLOW}result
    
    # ${COMPREPLY[@]}
    # "

    #printf "\nyour command > ${GREEN}${COMP_WORDS[*]}${NO_COLOR}"

    printf "\nyour command > ${GREEN}${COMP_LINE:0:$COMP_POINT}${RED}${COMP_LINE:$COMP_POINT}${NO_COLOR}"


    return 0
}

add_to_completion() {
  path="$1"

  for file in ${path}/*; do
      name=${file##*/}
      if [[ -f "$file" ]]; then
        #info.log \"added completion for: \$name\"
        complete -F _oo_completion $name -o bashdefault -o default -o nospace
      fi
  done

  echo added completions for commands in ${path}
}

if [ -d ${BASH_COMPLETION_USER_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/bash-completion}/completions ] && ! shopt -oq posix; then
echo finding completions
for bcfile in ${BASH_COMPLETION_USER_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/bash-completion}/completions/*; do
    echo sourcing $bcfile
    . $bcfile
done
fi
complete -o nospace -o bashdefault -o default -F _oo_completion c2 

complete -F _oo_completion once
add_to_completion ${OOSH_DIR}
add_to_completion ${OOSH_DIR}/su
add_to_completion ${OOSH_DIR}/ng
add_to_completion ${OOSH_DIR}/external