#!/usr/bin/env bash

printf -v jq '.[] | "\(.index) \(.uri) %s\(.tags)%s \(.title)"' "$(tput setaf 7)" "$(tput sgr0)"

main() {
  local choice=()
  mapfile -t choice < <(buku -p -j |
    jq -r "$jq" |
    SHELL=bash fzf \
    --ansi \
    --tac \
    --bind='enter:execute(qutebrowser {2})' \
    --expect='ctrl-d,ctrl-e' \
    --delimiter=' ' \
    --height=100% \
    --no-hscroll \
    --preview-window=down \
    --preview='buku -p {1}; lynx -dump {2}' \
    --query="$*" \
    --with-nth=3..)

  selection=${choice[@]:1}

  case ${choice[0]} in
    ctrl-d)
      buku -d ${selection[0]%% *}
      main
      ;;
    ctrl-e)
      buku -w ${selection[0]%% *}
      main
      ;;
  esac
}

main "$*"
