#!/usr/bin/env sh
#
# dependencies: f-rg-preview
#
# ---
# source: https://github.com/dandavison/tools

rg_args='-i --hidden -g "!.git/*"'
if [ "$1" = "--exclude-tests" ]; then
  rg_args='-i --hidden -g "!.git/*" -g "!*test*" -g "!*mock*" -g "!openapiv*"'
  shift
fi

RG="rg ${rg_args} --color=always"
if [ -f .rg-config ]; then
  RG="RIPGREP_CONFIG_PATH=.rg-config ${RG}"
fi

EDITOR=${EDITOR:-vim}
RG="rg ${rg_args} --color=always"
DELTA="delta --dark --grep-output-type classic"

fzf() {
  command fzf \
    --layout reverse \
    --info hidden \
    --prompt ' ' \
    --ansi \
    --bind 'ctrl-k:kill-line' \
    --bind 'alt-right:forward-word' \
    --bind 'alt-left:backward-word' \
    --preview-window 'up,70%' \
    "$@"
}

initial_command() {
  if [ -n "$1" ]; then
    "${RG}" --json "$*" . 2>/dev/null
  fi
}

# hack: to trigger display of initial results, we append a space then delete it on start
initial_command "$@" | ${DELTA} \
  | fzf -d: \
    --query="$* " \
    --disabled \
    --bind='start:backward-delete-char' \
    --bind="change:reload:${RG} --json {q} . | ${DELTA}" \
    --bind='enter:execute:v {1}:{2}' \
    --preview="[[ -n {1} ]] && f-rg-preview {1} {2}"
