#!/bin/sh

set -e

indexFile="${HOME}/.local/share/bm.db"
# COLUMNS="${COLUMNS:-$(stty size 2>/dev/null | cut -d' ' -f2 || echo "80")}"
# cols=$((COLUMNS - 20))

getTmpFile() {
  mktemp --tmpdir smarky-script-XXXXXX.sh
}

initDatabase() {
  sqlite3 "${indexFile}" "
    CREATE TABLE if not exists bookmarks (
      id INTEGER PRIMARY KEY,
      url TEXT,
      description TEXT
    );"
}

usage() {
  printf %s "\
$(basename "$0")

commands:
  [a]dd         - Add a mark to the index.  [description]
  [c]reate      - Add a mark to the index.  [description]
  [l]ist        - List all added bookmarks.
  [p]ick   [id] - Get url by id.
  [s]elect [id] - Get url by id.
  [u]pdate [id] - Edit a mark in the index. [description]
  rm       [id] - Remove url by id.
  [h]elp        - Display this message.

flags:
  -h, --help    - Display this message.
"
}

create() {
  initDatabase
  description="$1"
  cmdline="$2"
  tmpFile="$(getTmpFile)"

  if [ "$#" -lt 2 ]; then
    ${EDITOR:-vim} "${tmpFile}"
    cmdline="$(cat "${tmpFile}")"
  fi

  # shellcheck disable=SC2312
  sqlite3 "${indexFile}" "
    INSERT INTO bookmarks (url, description) values (
      '$(echo "${cmdline}" | sed "s/'/''/g")',
      '$(echo "${description}" | sed "s/'/''/g")'
    );"

  rm "${tmpFile}"
  echo "Bookmark created successfully: ${description}"
}

remove() {
  if [ "$#" -lt 1 ]; then
    usage
    exit 2
  fi
  sqlite3 "${indexFile}" "DELETE FROM bookmarks WHERE id = $1;"
}

get() {
  if [ "$#" -lt 1 ]; then
    usage
    exit 1
  fi
  sqlite3 "${indexFile}" "SELECT url FROM bookmarks WHERE id = $1;"
}

list() {
  if [ -t 1 ]; then
    filter="cut -c -78"
  else
    filter="cat -"
  fi
  sqlite3 -column -noheader "${indexFile}" "
    SELECT
      id, replace(description, CHAR(10), '  '), replace(url, CHAR(10), '  ')
    FROM bookmarks;" | ${filter}
}

update() {
  markId="${1:--1}"
  description="$2"
  cmdline="$3"
  tmpFile="$(getTmpFile)"
  exists="$(sqlite3 "${indexFile}" "SELECT 1 FROM bookmarks WHERE id = ${markId};")"

  if [ "$#" -lt 1 ]; then
    usage
    exit 3
  fi
  [ -z "${exists}" ] && (echo "Bookmark ID ${markId} doesn't exist." && exit 4)

  if [ "$#" -lt 3 ]; then
    get "${markId}" > "${tmpFile}"
    ${EDITOR:-vim} "${tmpFile}"
    cmdline="$(cat "${tmpFile}")"
  fi

  if [ -n "${description}" ]; then
    descriptionSet="description = '$(echo "${description}" | sed "s/'/''/g")',"
  fi

  # shellcheck disable=SC2312
  sqlite3 "${indexFile}" "
    UPDATE bookmarks
    SET
      ${descriptionSet}
      url = '$(echo "${cmdline}" | sed "s/'/''/g")'
    WHERE id = ${markId};"

  rm "${tmpFile}"
  echo "Bookmark ID ${markId} updated successfully."
}

main() {
  # initDatabase
  case "$1" in
    a|add) shift; create "$@" ;;
    c|create) shift; create "$@" ;;
    h|help) usage; exit 0 ;;
    l|list) shift; list "$@" ;;
    p|pick) shift; get "$@" ;;
    s|select) shift; get "$@" ;;
    rm) shift; remove "$@" ;;
    up|update) shift; update "$@" ;;
    *) usage; exit 0 ;;
  esac
}

main "$@"

# ============================================================================
# fzf-smarky-pick-command() {
#   setopt localoptions noglobsubst noposixbuiltins pipefail 2>/dev/null
#   local selected previewcmd="smarky select \$(cut -d' ' -f1 <<< {})"

#   type bat >/dev/null 2>&1 && \
#     previewcmd="bat -l sh --color always --decorations never <($previewcmd)"

#   selected="$(smarky list | fzf --height 40% --tiebreak=index \
#     --preview "$previewcmd" | cut -d' ' -f1 | xargs -r smarky select)"

#   [ -n "$selected" ] && LBUFFER="$selected"
#   zle reset-prompt
# }

# fzf-smarky-next-field() {
#   setopt localoptions noglobsubst noposixbuiltins pipefail 2>/dev/null
#   [ -z "$RBUFFER" ] && CURSOR=0
#   local fieldstart='{{' fieldend='}}'
#   local subtracted="${RBUFFER#*$fieldstart}" offset
#   offset=$(( ${#RBUFFER} - ${#subtracted} - ${#fieldstart} + $CURSOR ))
#   CURSOR=offset; RBUFFER="${RBUFFER#*$fieldend}"
# }

# zle -N fzf-smarky-pick-command
# bindkey '^J' fzf-smarky-pick-command

# zle -N fzf-smarky-next-field
# bindkey '^G' fzf-smarky-next-field
