#!/usr/bin/env sh
#
# snip - snippets manager
# dependencies: bat | fd | rg
# optional: fzf | gum | neovide

set -eu

if [ -z "${SNIPPETS_PATH}" ]; then
  SNIPPETS_PATH="${HOME%/}"'/.dotfiles/snippets'
else
  SNIPPETS_PATH=$(echo "${SNIPPETS_PATH-}" | sed "s|^~/|${HOME}/|")
fi

if [ -z "${IDE-}" ]; then
  if command -v nvim >/dev/null 2>&1; then
    IDE=${IDE:-nvim}
  elif command -v neovide >/dev/null 2>&1; then
    IDE=${IDE:-neovide}
  elif command -v v >/dev/null 2>&1; then
    IDE=${IDE:-v}
  elif command -v cot >/dev/null 2>&1; then
    IDE=${IDE:-cot}
  else
    IDE=${IDE:-${EDITOR:-vi}}
  fi
fi

if [ -z "${TUI_EDITOR-}" ]; then
  if command -v nvim >/dev/null 2>&1; then
    TUI_EDITOR=${TUI_EDITOR:-nvim}
  elif command -v neovide >/dev/null 2>&1; then
    TUI_EDITOR=${TUI_EDITOR:-neovide}
  elif command -v v >/dev/null 2>&1; then
    TUI_EDITOR=${TUI_EDITOR:-v}
  else
    TUI_EDITOR=${TUI_EDITOR:-${EDITOR:-vi}}
  fi
fi

usage() {
  printf %s "\
$(basename -- "$0")
  a simple script to search/edit/manage snippets

$(basename -- "$0") [command] [search_pattern]

commands:
  [a]ll         - Open all snippets with a name that matches the pattern in IDE.
  [c]lip        - Copy first snippet with name that matches the pattern.
  [e]dit        - Open first snippet with name that matches pattern in TUI_EDITOR.
  [f]d          - Search and lists all snippets with name that matches pattern.
  [g]r          - Grep text inside all snippets.
  [h]           - Display this message.
  [l]s          - List snippets.
  [n]ew         - New snippet with name.
  [o]pen        - Open root folder of snippets using IDE.
  [r]g          - Grep text inside all snippets.
  [s]how        - Show all snippets with a name that matches pattern.

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

examples:
  fd \".*\"                  # List all file and folders
  rg env,bash                # Grep \"word bash\" in all files
  rg \"env bash\"            # Grep \"word bash\" in all files
  show \"move to\"           # Show all snippets that contains \"move to\"
  edit -e json \"message\"   # Edit json (.json) and name contains \"message\"
  all -e json \".*\"         # Edit snippets type json (extension .json)

env vars:
  SNIPPETS_PATH
  IDE
  TUI_EDITOR

dependencies:
  bat     - [https://github.com/sharkdp/bat]
  fd      - [https://github.com/sharkdp/fd]
  fzf     - [https://github.com/junegunn/fzf] [optional]
  neovide - [https://github.com/neovide/neovide] [optional]
  rg      - [https://github.com/BurntSushi/ripgrep]
"
  exit 0
}

# tmpfile="$(mktemp "$(basename "$0")".XXXXXX)" || tmpfile="${TMPDIR:-/tmp}"/snip$$
# trap 'rm -- "$tmpfile"' EXIT

new_script() {
  file="$1"
  cd "${SNIPPETS_PATH-}" || return
  if [ -e "${SNIPPETS_PATH}"/"${file}" ]; then
    echo "File already exists."
    printf '%s' "Do you want to edit existing snippet?" '[y/n] '
    read -r ans
    case "${ans}" in
      y* | Y*)
        exec "${EDITOR:-vi}" "${file}" '+$'
        ;;
      *)
        return
        ;;
    esac
  else
    touch "${file}"
    exec "${EDITOR:-vi}" "${file}" '+$'
  fi
}

fuzzy_snippets() {
  if command -v fzf >/dev/null 2>&1; then
    # shellcheck disable=SC2016
    # no selection => open the current line in $EDITOR. || build quickfix list
    # OPENER='if [ "${FZF_SELECT_COUNT-}" -eq 0 ]; then "${EDITOR}" {1} +{2}; elif [ "${EDITOR}" = vim ] || [ "${EDITOR}" = nvim ]; then "${EDITOR}" +cw -q {+f}; else "${EDITOR}" {+1}; fi'
    # --expect=alt-n
    # --bind "enter:execute(${EDITOR:-vi} {1} +{2})"
    # --bind 'ctrl-k:preview-up,ctrl-j:preview-down'
    # --bind "f1:execute(less -f ${SNIPPETS_PATH}/{q} )+abort" \
    # --preview-window='default:left,60%,noborder' \
    # --margin=5%,10%,5%,5% --border=none
    # --tmux center,80%,border-native
    # --tmux top,80%,40% \
    # fd . "${SNIPPETS_PATH}" | fzf --ansi --exit-0 --query "${*:-}" \
    # fd . --exec-batch ls -atp \
    # fd .
    # --delimiter="/" --with-nth=1,2 \
    # --tiebreak=begin,index \

    cd "${SNIPPETS_PATH}" || return
    file=$(
      lr -f '%p\n' -t 'type == f' -oM \
        | fzf --query="${*-}" --print-query \
          --tiebreak=chunk,length,index \
          --ansi --layout=reverse --height=90% --margin=4%,2%,4%,2% \
          --info=inline-right \
          --multi \
          --bind='ctrl-\:toggle-preview' \
          --bind='ctrl-/:change-preview-window(right,70%,border-bottom|hidden|)' \
          --bind="ctrl-y:execute-silent(ruby -e 'puts ARGV' {+} | pbcopy)+abort" \
          --bind="ctrl-o:execute(${EDITOR} {+})+abort" \
          --bind="alt-e:execute(${EDITOR} {+})" \
          --bind="alt-n:execute(${EDITOR} ${SNIPPETS_PATH}/{q} >/dev/tty)+abort" \
          --preview='bat --style=snip --color=always --line-range :500 {}' \
          --preview-window='up,50%,border-line'
    )
    # --preview-window 'nohidden:right,border-line' \
    # EX_NOINPUT 66
    # EX 130: Interrupt
    ret="$?"
    if [ "${ret}" -eq 130 ]; then
      # cd || return
      return 1
    fi
    if [ "${ret}" = 0 ]; then
      file=$(echo "${file}" | tail -n1)
      # shellcheck disable=SC2002
      # cat "${file}" | tr -d "\n" | pbcopy
      pbcopy <"${file}"
      bat "${file}"
      # cd || return
      # exit 0
    fi
  elif command -v gum >/dev/null 2>&1; then
    # shellcheck disable=SC2312
    gum style --border normal --margin "1" --padding "1 2" \
      --border-foreground 212 \
      "HLPR $(gum style --foreground 212 'easy snippet finder & helper')"

    printf '%s' "what do you need help with?"
    printf "\n"
    sleep 0.5

    CHOICE=$(gum choose "View snippet" "Edit snippet" "Create group" "Delete group")

    if [ "${CHOICE}" = "Edit snippet" ]; then
      ("${EDITOR:-vi}" "${SNIPPETS_PATH}")

    elif [ "${CHOICE}" = "View snippet" ]; then

      FILES=$(
        cd "${SNIPPETS_PATH}" || return 1
        gum filter --placeholder "Choose a file"
      )
      bat --force-colorization "${SNIPPETS_PATH}"/"${FILES}"

    elif [ "${CHOICE}" = "Create group" ]; then

      DIRN=$(gum input --placeholder "Enter snippet group name")
      [ -f "${SNIPPETS_PATH}"/"${DIRN}" ] \
        || "${EDITOR:-vi}" "${SNIPPETS_PATH}"/"${DIRN}"

    elif [ "${CHOICE}" = "Delete group" ]; then

      FILES=$(
        cd "${SNIPPETS_PATH}" || return 1
        gum filter --placeholder "Choose a file to DELETE"
      )
      gum confirm "do you want to delete?" \
        && (trash-put "${SNIPPETS_PATH}"/"${FILES}" \
          || rm -f "${SNIPPETS_PATH}"/"${FILES}")
    fi
  else
    usage
  fi
}

if [ "$#" -eq 0 ]; then
  fuzzy_snippets
fi

if [ "$#" -gt 0 ]; then
  case "$1" in
    a | all)
      shift
      if [ "$#" -eq 0 ]; then
        printf '%s\n' "$(basename "$0"): a|all [snippet name]"
        exit 1
      else
        if [ "$#" -eq 1 ]; then
          queries=$(echo "${@-}" | sed -e 's/,/|/g' -e 's/ /|/g')
          # queries=$(echo "${@-}" | sed 's/,/|/g')
          # shellcheck disable=SC2046,SC2312
          "${IDE}" $(fd "${queries-}" "${SNIPPETS_PATH}" | head -5)
        else
          queries=$(echo "${@-}" | sed -e 's/,/|/g' -e 's/ /|/g')
          # queries=$(echo "${2-}" | sed 's/,/|/g')
          # shellcheck disable=SC2046,SC2312
          "${IDE}" $(fd --extension="$1" "${queries-}" "${SNIPPETS_PATH}" | head -5)
        fi
      fi
      # # shellcheck disable=SC2046,SC2312
      # "${IDE}" $(fd "${queries-}" "${SNIPPETS_PATH}" | head -5)
      ;;
    c | clip)
      shift
      if [ "$#" -eq 0 ]; then
        printf '%s\n' "$(basename "$0"): c|clip [snippet name]"
        exit 1
      else
        queries=$(echo "${@-}" | sed 's/,/|/g')
        file="$(fd --glob "${queries-}" "${SNIPPETS_PATH}" | head -1)"
        # shellcheck disable=SC2002
        cat "${file}" | pbcopy
        bat "${file}"
        # pbcopy "$(fd --glob "${argument-}" "${SNIPPETS_PATH}" | head -1)"
        # bat "$(fd --glob "${argument-}" "${SNIPPETS_PATH}" | head -1)"
      fi
      ;;
    e | edit)
      shift
      if [ "$#" -eq 0 ]; then
        printf '%s\n' "$(basename "$0"): e|edit [snippet name]"
        exit 1
      else
        if [ "$#" -eq 1 ]; then
          queries=$(echo "$1" | sed 's/,/|/g')
          # shellcheck disable=SC2046,SC2312
          "${TUI_EDITOR}" $(fd "^${queries-}" "${SNIPPETS_PATH}" | head -1)
        else
          queries=$(echo "$2" | sed 's/,/|/g')
          # shellcheck disable=SC2046,SC2312
          "${TUI_EDITOR}" $(fd --extension="$1" "${queries-}" "${SNIPPETS_PATH}" | head -5)
          # || printf '%s\n' "No snips with name $1" \
          #   exit 1
        fi
      fi
      ;;
    f | fd)
      shift
      if [ "$#" -eq 0 ]; then
        printf '%s\n' "$(basename "$0"): f|find [snippet name]"
        exit 1
      fi
      # "${@: -1}" start at the last positional parameter
      # fd "${@:2:$#-2}" "${@: -1}" "${SNIPPETS_PATH}"
      queries=$(echo "${@-}" | sed 's/,/|/g')
      # fd "${queries-}" "${SNIPPETS_PATH}" | sed "s|${SNIPPETS_PATH}/||"
      fd "${queries-}" "${SNIPPETS_PATH}"
      ;;
    g | gr)
      shift
      if [ "$#" -eq 0 ]; then
        printf '%s\n' "$(basename "$0"): g|grep [snippet name]"
        exit 1
      fi
      # rg "${@:2:$#-2}" "${@: -1}" "${SNIPPETS_PATH}"
      queries=$(echo "${@-}" | sed -e 's/,/|/g' -e 's/ /|/g')
      rg --hyperlink-format=kitty "${queries-}" "${SNIPPETS_PATH}"
      ;;
    l | ls)
      cd "${SNIPPETS_PATH}" || return "${?:-1}" \
        && ls
      ;;
    n | new)
      shift
      if [ "$#" -eq 0 ]; then
        printf '%s\n' "$(basename "$0"): n|new [snippet name]"
        exit 1
      else
        new_script "$@"
      fi
      ;;
    o | open)
      case "${IDE}" in
        nvim | vim | v)
          "${IDE}" -c ":lcd %:p:h" "${SNIPPETS_PATH}"
          ;;
        neovide)
          "${IDE}" -- -c ":lcd %:p:h" "${SNIPPETS_PATH}"
          ;;
        *)
          "${IDE}" "${SNIPPETS_PATH}"
          ;;
      esac
      ;;
    r | rg)
      shift
      if [ "$#" -eq 0 ]; then
        printf '%s\n' "$(basename "$0"): r|rg [snippet name]"
        exit 1
      else
        # rg "${@:2:$#-2}" "${@: -1}" "${SNIPPETS_PATH}"
        # echo "trap stty" | sed -e 's/,/|/g' -e 's/ /|/g'
        queries=$(echo "${@-}" | sed -e 's/,/|/g' -e 's/ /.*/g')
        rg --hyperlink-format=kitty "${queries-}" "${SNIPPETS_PATH}"
      fi
      ;;
    s | show)
      shift
      if [ "$#" -eq 0 ]; then
        printf '%s\n' "$(basename "$0"): s|show [snippet name]"
        exit 1
      else
        queries=$(echo "${@-}" | sed -e 's/,/|/g' -e 's/ /|/g')
        fd --type=file "${queries-}" "${SNIPPETS_PATH}" \
          --exec-batch bat --style=header --paging never
      fi
      ;;
    h)
      usage
      ;;
    -h | --help)
      usage
      ;;
    *)
      cd "${SNIPPETS_PATH}" || exit 1 \
        && fuzzy_snippets "${*:-}"
      ;;
  esac
fi
