#!/usr/bin/env bash
#
# zn - create a new note
# dependencies: std

# shellcheck shell=bash

NOTE_DIR=${NOTE_DIR:-${HOME}/notes}

log() (
  if tty -s; then
    lcol='\033[1;33m'
    lcol2='\033[1;36m'
    lclr='\033[m'

    printf "%b%s %b%s%b %s\n" \
      "${lcol}" "${3:-->}" "${lclr}${2:+${lcol2}}" \
      "$1" "${lclr}" "$2" >&2
  else
    printf "%s: %s%s%s %s\n" "${3:-$0}" \
      "${2:+[}" "$1" "${2:+]}" "$2"
  fi
)
die() {
  log "$1" "$2" "ERROR"
  exit 1
}

export FZF_DEFAULT_OPTS="--color pointer:red --color bg+:bright-black"

printf "Title: "
title=
read -r title

# shellcheck disable=SC2312
id=$(printf '%s' "${title}" \
  | tr -d "\"'.,!:;+=@#$%&*\`~\\/()[]{}|" \
  | tr '[:upper:]' '[:lower:]' \
  | sed 's/ /-/g' \
  | head -c 32)
fname="${id}.md"
path="${DIR}/${fname}"
[ -f "${path}" ] && die "${fname} already exists"
printf "Creating '%s'\n" "${fname}"

tags=$()

tags=
while :; do
  prompt="Tags: "
  [ -z "${tags}" ] || prompt="Tags (${tags/ /}): "

  # shellcheck disable=SC2312
  taglist="$(rg -I '[\^ ]#[a-z]+' "${DIR}" | tr ' ' '\n' | tr -d '#' | sort -u)"
  fzfout="$(fzf --bind=enter:replace-query+print-query --reverse --prompt="${prompt}" <<<"${taglist}")"
  [ "$?" = 130 ] && break
  tags="${tags} #$(tr -d '\n' <<<"${fzfout}")"
done
# shellcheck disable=SC2250
tags="${tags/ /}" # remove leading space
printf "Tags: %s\n" "${tags}"

touch "${path}"
printf '%s\n' "${title}" >>"${path}"
printf '%s\n' "${title}" | sed 's/./=/g' >>"${path}"
printf "\n" >>"${path}"
date "+%B %d, %Y" >>"${path}"
printf "\n" >>"${path}"
printf '%s\n' "${tags}" >>"${path}"
printf "\n" >>"${path}"

${EDITOR:-vi} "${path}"
