# inspired by https://oppi.li/posts/jjj/
# using what i made for
# - https://git.pvv.ntnu.no/pederbs/just-nixpkgs
# - https://git.pvv.ntnu.no/pederbs/config/src/commit/5a2927372b180d7bfcf67f93151f3756bc4f26df/users/pbsds/home/profiles/headless/fzf.nix

# TODO: use gum/fzf to make a menu with various modes
#       * [ ] mode with git log --oneline --all
#       * [ ] mode with branches/tags
#       * [ ] mode with commit from a specific branch/tag
#       * [ ] mode with commit ranges (aaa..bbb)
#       * [ ] mode with multiple commits in single command
#       * [ ] mode with multiple commits across multiple command like https://arch1t3cht.org/blog/jjjj/

if command -v git  >/dev/null \
&& command -v fzf  >/dev/null \
&& command -v cut  >/dev/null \
&& command -v head >/dev/null
then

fgit() {
  local -a git_color=()
  if [[ -t 2 ]]; then
    git_color+=( --color=always )
  fi

  local -a fzf_args=(
    --height=15
    # --multi

    --reverse
    --bind 'home:first'
    --bind 'end:last'
    --cycle
    --ansi
    --prompt "git $* "
    --preview 'git show "$(cut -d" " -f1 <<< {} )" '"${git_color[*]}"' --stat | head -n$FZF_PREVIEW_LINES'
    --preview-window follow
  )

  local commit_id="$( git log --oneline "${git_color[@]}" | fzf "${fzf_args[@]}" | cut -d" " -f1 )"

  if [[ -n "$commit_id" ]]; then
    # recreate 'set -x' to avoid a subshell
    >&2 echo "+$(printf " %q" git "$@" "$commit_id")"

    git "$@" "$commit_id"
  fi
}

fi
