#!/bin/sh
#
# live-preview REPL with fzf
#
# ---
# see: https://github.com/pawelduda/fzf-live-repl
# see: https://gist.github.com/reegnz/b9e40993d410b75c2d866441add2cb55#file-jq-repl
# see: https://github.com/reegnz/jq-zsh-plugin

# ruby repl
echo '' | fzf --print-query --preview 'ruby -r csv -r json -e {q}'


# jq repl
if [ -z "$1" ] || [ "$1" = "-" ]; then
  input=$(mktemp)
  trap 'rm -f "$input"' EXIT
  cat /dev/stdin >"${input}"
else
  input="$1"
fi

echo '' \
  | fzf \
    --disabled \
    --preview-window='up:90%' \
    --print-query \
    --preview "jq --color-output -r {q} ${input}"


# if 1st arg is '-' read from stdin
# if 1st arg is '--' take the command after it verbatim and execute it to get the input
# if 1st arg is anything else, treat it as a file
set -eu

export JQ_REPL_JQ="${JQ_REPL_JQ:-jq}"

if [ -n "${1:-}" ] && [ "$1" != "-" ] && [ "$1" != "--" ]; then
  input="$1"
  output=$(mktemp)
  trap 'rm -f "$output"' EXIT
else
  input=$(mktemp)
  output=$(mktemp)
  trap 'rm -f "$input" "$output"' EXIT
fi

if [ -z "${1:-}" ] || [ "$1" = "-" ]; then
  cat /dev/stdin >"$input"
fi
if [ "${1:-}" = "--" ]; then
  shift
  export FZF_JQ_REPL_COMMAND="$* > $input; jq-paths <$input"
else
  export FZF_JQ_REPL_COMMAND="jq-paths < \"$input\""
fi

fzf_notation_types="~!@#$%^&*;/|"
skip_notation="$(echo "$FZF_JQ_REPL_COMMAND" | sed -E "s,[^$fzf_notation_types],,g")"
fzf_notation="$(echo "$fzf_notation_types" | sed -E "s,[$skip_notation],,g" | head -c 1)"
if [ -z "$fzf_notation" ]; then
  # fall back to default and hope for the best
  fzf_notation="#"
fi

# default ignore
FZF_COPY_TO_CLIPBOARD="execute-silent(ignore)"

# other platforms can be supported here as needed
command -v xclip > /dev/null && \
  FZF_COPY_TO_CLIPBOARD="execute-silent(echo -n {} | xclip -in -sel clip)+abort"

eval "$FZF_JQ_REPL_COMMAND" |
  fzf \
    --preview "jq-repl-preview {q} $input $output" \
    --preview-window="down:90%" \
    --height="99%" \
    --query="." \
    --bind "tab:replace-query,return:print-query" \
    --bind "ctrl-p:preview-up,ctrl-n:preview-down" \
    --bind "ctrl-alt-p:preview-half-page-up,ctrl-alt-n:preview-half-page-down" \
    --bind "shift-up:preview-up,shift-down:preview-down" \
    --bind "alt-up:preview-page-up,alt-down:preview-page-down" \
    --bind "ctrl-y:$FZF_COPY_TO_CLIPBOARD" \
    --bind "ctrl-r:reload${fzf_notation}${FZF_JQ_REPL_COMMAND}${fzf_notation}+refresh-preview"
