#!/bin/sh

# shellcheck source=/dev/null
. "$(fzf-share)/completion.bash"
# Disable fzf key-bindings
# readline > fzf
# . "$(fzf-share)/key-bindings.bash"

export FZF_CTRL_T_OPTS='
  --preview "(cat {} || tree -C {}) 2> /dev/null"
  --select-1
  --exit-0
'

export FZF_ALT_C_OPTS='--preview "tree -C {} | head -200"'

fzg() {
  fn=$(git grep -n "$1" | \
         cut -d: -f -2  | \
         fzf --select-1 \
             --exit-0   \
             --preview "echo {}       | \
                          cut -d: -f1 | \
                          xargs -I% awk -v bounds=15 -v pat=\"$1\" -v n=\$(echo {} | cut -d: -f2) '
                            (n - bounds < NR) && (NR < n + bounds) && (NR != n) { print }
                            NR==n { gsub(pat, \"\033[1;33m&\033[1;000m\"); print }
                          ' %")
  if [ -n "$fn" ]; then
    f="$(echo "$fn" | cut -d: -f1)"
    n="$(echo "$fn" | cut -d: -f2)"
    # shellcheck disable=2068
    history -s fzg $@
    history -s vi "+$n" "$f"
    vi "+$n" "$f"
  fi
}

f() {
  profile="f-shell-function$(pwd | sed -e 's_/_-_g')"
  file="$(git ls-files | remembering -p "$profile" -c "fzf --select-1 --exit-0 --query \"$2\" --preview 'cat {}'")"
  if [ -n "$file" ]; then
    # shellcheck disable=2068
    history -s f $@
    history -s "$1" "$file"
    "$1" "$file"
  fi
}

V_FILES='
Sync/TODOs.md
tmp/scratch.txt
annex/txt/things.md
annex/bin/misc/git/mrconfig.ini
archive/vid/playlist.txt
dev/libre/others/dinheiros/money.ledger
'

v() {
  # I want to keep the pre-defined order
  f="$(echo "$V_FILES" | awk /./ | fzf --select-1 --exit-0 --query "$1")"
  if [ -n "$f" ]; then
    history -s v "$@"
    # shellcheck disable=2088
    history -s vi "~/$f"
    echo "$f"
    vi "$HOME/$f"
  fi
}
