#!/usr/bin/env sh

RELOAD='reload:rg --column --color=always --smart-case {q} || :'
# shellcheck disable=SC2016
OPENER='if [ "${FZF_SELECT_COUNT}" -eq 0 ]; then
          vim {1} +{2}     # no selection. open the current line in Vim.
        else
          vim +cw -q {+f}  # build quickfix list for the selected items.
        fi'
fzf --disabled --ansi --multi \
   --bind="enter:become:${OPENER}" \
   --bind="ctrl-o:execute:${OPENER}" \
   --delimiter=":" \
   --preview='bat --style=full --color=always --highlight-line {2} {1}'

# vim +cw -q {+f} needs some explanation
#   +cw tells Vim to execute :cw command to open the quickfix window
#   -q {+f} makes Vim start in quickfix mode using the error file {+f}
#
# so what is {+f}?
# it's a placeholder expression for a temporary file containing selected items
# it's a combination of two flags: + and f. see: man fzf(1) for more information

RELOAD='reload:rg --column --color=always --smart-case {q} || :'

RELOAD='reload:rg --column --color=always --line-number --no-heading --smart-case {q} || :'

RELOAD='reload:rg --hidden --follow --glob "!.git" --line-number --no-heading --column --color=always --smart-case {q} || :'

# shellcheck disable=SC2016
OPENER='if [ ${FZF_SELECT_COUNT} -eq 0 ]; then
          "${EDITOR}" {1} +{2}     # no selection. open the current line in $EDITOR.
        elif [ ${EDITOR} = vim ] || [ ${EDITOR} = nvim ]; then
          "${EDITOR}" +cw -q {+f}  # build quickfix list for the selected items.
        else
          "${EDITOR}" {+1}
        fi'

# shellcheck disable=SC2016
OPENER='if [ "${FZF_SELECT_COUNT}" -eq 0 ]; then
          "${EDITOR}" {1} +{2}     # no selection. open the current line in $EDITOR.
        else
          "${EDITOR}" +cw -q {+f}  # build quickfix list for the selected items.
        fi'

fzf --no-height --tmux 100% --disabled --ansi --multi --query "${*:-}" \
    --bind "start,change:${RELOAD}" \
    --bind "enter:become:${OPENER}" \
    --bind "ctrl-o:execute:${OPENER}" \
    --bind 'alt-a:select-all,alt-d:deselect-all,ctrl-/:toggle-preview' \
    --delimiter : \
    --preview 'bat --color=always --highlight-line {2} {1}' \
    --preview-window 'default:up,border-bottom,~3,+{2}+3/3'

    # fzf --ansi --disabled --query "${*:-}"
    # --bind "start:reload:${RG_PREFIX} {q}"
    # --bind "change:reload:sleep 0.1; ${RG_PREFIX} {q} || true"
    # --bind "enter:execute(${EDITOR:-vim} {1} +{2})"
    # --preview 'bat --color=always {1} --highlight-line {2}'
    # --preview-window 'default:up,60%,border-bottom,+{2}+3/3,~3'
    # --height 85%
    # --bind "enter:execute(${EDITOR:-vim} {1} +{2})"
    # --bind="enter:execute(echo {+} | xargs -o ${EDITOR:-vim})"
    # --bind="alt-e:execute(echo {+} | xargs -o ${EDITOR:-vim})"
    # --bind "ctrl-y:execute-silent(echo {+} | pbcopy)"
    # --preview-window '~4,+{2}+4/3,<80(up)'
