#!/bin/sh -e

# setting gkeys dir as a var= one option works and other doesn't & vice versa
GKEYS_DIR="${XDG_DATA_HOME:-${HOME%/}/.local/share}"'/gkeys'

bat_read() {
  bat --paging=always --wrap=auto --style=snip \
    "${GKEYS_DIR}/$*" --file-name="${*:-}"
}

search() {
  rg "${3:-^}" "${GKEYS_DIR}/${2}" | fzf --delimiter / --with-nth -1
}

fuzzy() {
  file="$(
    find "${GKEYS_DIR-}"/* -maxdepth 1 -type f | fzf --ansi -m \
      --delimiter / --with-nth -1 \
      --preview-window=:nohidden \
      --preview='([ -f {} ] && (bat --style=numbers --color=always -l bash {})) \
        || ([ -d {} ] && (tree -C {} | less)) \
        || echo {} 2>/dev/null | head -200'
  )"
  [ -n "${file}" ] && bat --paging=always --wrap=auto --style=snip "${file}"
}

edit() {
  if [ -z "$1" ]; then
    printf '%s\n' "Nothing selected."
    return 1
  else
    ${EDITOR:-vi} "${GKEYS_DIR}/$2"
  fi
}

case "$1" in
  -e | --edit)
    edit "$@"
    ;;
  -f | --fzf)
    fuzzy "$@"
    ;;
  -s | --search)
    search "$@"
    ;;
  *)
    bat_read "$@"
    ;;
esac
