#!/usr/bin/env bash

IFS=

# Allow ** glob and Bash extended globbing
shopt -s globstar extglob nullglob

# Set up the template variable.
helper_bin=fzf-ctags-helper
lib_src=fzf-ctags-lib
helper="%FZF_DIR%/bin/$helper_bin"
lib="%FZF_DIR%/bin/$lib_src"

# Setup the colorization preview helper.
if [[ $helper = %*%* ]]; then
    # Find the helper if run directly, without installing.
    help_dir=${0%/*}
    [[ $0 != /* ]] && help_dir=$PWD/$help_dir
    lib="$help_dir/$lib_src"
    helper=$help_dir/$helper_bin
    # Found? Try cat if not.
    [[ ! -f $helper ]] && helper=cat
    [[ ! -f $lib ]] && {
            #printf "Library fzf-ctags-lib not found, exiting.\n"
            exit 1
    }
fi

# Load shared functions library.
source "$lib"
export FZF_CTAGS_LIB="$lib"

# Which mode? Symbol, or surrounding text?
if [[ $1 == symbol-only ]]; then
    q=2
elif [[ -z $1 || $1 = text ]]; then
    q=1
fi

typeset tags tags_path ptags="/tmp/.TAGS.z-$$"
get_tags && tags="$REPLY"

# Is there any TAGS file to read?
if [[ -z $tags || ! -f $tags ]]; then
    #printf "No \e[38;5;208mTAGS\e[0m file found, exiting…\e[0m\n"
    #printf "(\`univeral ctags\` is recommended tool to generate one;\n"
    #printf "homepage: https://github.com/universal-ctags/ctags).\n"
    exit 1
fi

tags_path="${tags%/TAGS}"
# Sort out the symbol to open at.
type &>/dev/null sed && sed=sed
type &>/dev/null ged && sed=gsed

command $sed -r -n $'/^\x0c$/ { n; s/,[^,]*$//;s/^/\x02/; h; d;}; G; y/\\n/,/; p' "$tags" > "$ptags"

line="$(fzf --preview="printf '%s' {} |$helper" --delimiter '\177' --with-nth $q < <( $sed -r -e 's/^\s+//' \
    -e 's/[\x01\x02]/\x7f/g' $ptags ))"
ret=$?

command rm -f $ptags

# Check if anything has been picked.
if (( ret != 0 )) || [[ -z $line ]]; then
    printf "\e[38;5;208mNo symbol has been picked out, nothing to do…\e[0m\n"
    exit 1
fi

# Split the input.
q=$(cut -d$'\x7f' -f2 <<< $line)
nr=$(cut -d$'\x7f' -f3 <<< $line)
nr=${nr%%,*}
e=$(cut -d$'\x7f' -f4 <<< $line)

# Use the user's configured editor falling back to vim.
ed="${VISUAL:-${EDITOR:-vim}}"
type $ed &>/dev/null || ed=emacs
type $ed &>/dev/null || ed=nano
if ! type $ed &>/dev/null; then
    #printf "\e[38;5;208mNo supported editor found, exiting…\e[0m\n"
    exit 1
fi


#printf "\nPicked: \e[1;38;5;39m$q\e[0m, opening: \
#\e[1;38;5;70m$ed\e[0m with the file: \e[1;38;5;140m$e\e[0m:\e[38;5;208m$nr\e[0m\n"

# Run editor on the selected file and line.
# The one-time loop is to emphasize the final step.
while 
    ( cd "$tags_path"; command "$ed" +"$nr" "$e"; )
    false
do true; done
