#!/usr/bin/env bash
#
# jqte - tmux-based jq explorer
# dependencies: entr | jq | tmux
#
# invocation:
# jqte [-p | --process filterfile] jsonfile

# the main invocation, just with a JSON file, is all that is needed,
# i.e. jqte somedata.json

# the other invocation, specifying a jq filter file with -p or --process,
# is for processing the JSON with the contents of the filter file, via
# entr.
#
# ---
# see: https://github.com/bfrg/vim-jqplay
# source: https://github.com/qmacro/dotfiles

# declare -r self=$0

setup() {

  # local jsonfile filterfile

  jsonfile=$1
  filterfile="$(mktemp)"

  # Start with basic filter
  echo "." >"${filterfile}"

  # Create a new tmux window to explore the data in the JSON file,
  # like this:

  # +---------------------+----------------------+
  # | output              | original JSON data   |
  # |                     |                      |
  # |                     |                      |
  # |                     |                      |
  # |          1          |                      |
  # |                     |                      |
  # |                     |          2           |
  # |                     |                      |
  # +                     +----------------------|
  # |                     | filter               |
  # |                     |          3           |
  # |                     |                      |
  # +---------------------+----------------------+

  # This assumes, btw, that you have pane numbering starting at 1
  # with set -w -g pane-base-index 1

  # The 'output' and 'original JSON data' panes (1 and 2) are
  # read-only, and the 'filter' pane (3) is a vim session to edit the
  # jq filter. Whenever that filter is modified the output is
  # re-rendered accordingly.

  tmux new-window \; \
    split-window -h \; \
    send-keys "vim ${jsonfile}" C-m \; \
    select-pane -t 2 \; \
    split-window -v -p 35 \; \
    send-keys "vim -c 'set filetype=jq' -c 'autocmd TextChanged,InsertLeave <buffer> silent write' ${filterfile}" C-m \; \
    select-pane -t 1 \; \
    send-keys "ls ${jsonfile} ${filterfile} | entr -c \"$0\" --process ${filterfile} ${jsonfile}" C-m \; \
    select-pane -t 3

}

process() {

  # local jsonfile filterfile

  filterfile=$1
  jsonfile=$2

  jq -f "${filterfile}" "${jsonfile}"

}

main() {

  # local process filterfile jsonfile

  if echo "$1" | grep -q '^--?p(rocess)?$' >/dev/null; then
    process=true
    shift
    filterfile=$1
    shift
  fi

  jsonfile=$1

  if [ -n "${process}" ]; then
    process "${filterfile}" "${jsonfile}"
  else
    setup "${jsonfile}"
  fi

}

main "$@"
