#!/bin/sh

set -eu

command="$1"
shift

maxwidth=80
padding_spaces=6

get_file() {
  echo "${HOME}/todo/$1"
}

pretty() {
  width=$(tput cols)
  width=$(( width < maxwidth ? width : maxwidth ))
  width=$(( width - padding_spaces ))
  fold --spaces --width "${width}" | sed -E -e '/^[^-]/s/^/      /'
}

new_task() {
  state="$1"
  shift
  file="$1"
  shift
  echo "- [${state}] $*" >> "${file}"
}

find_state() {
  grep "^- \[$1\]"
}

completed() {
  find_state 'x'
}

incomplete() {
  find_state ' '
}

import() {
  from=$1
  shift
  to=$1
  shift
  date=${from}
  while [ "${date}" != "${to}" ]; do
    incomplete <"${date}" >> "${to}"
    # output ISO-8601 date
    date=$(date -I -d "${date} + day")
  done
}

file=$(get_file "today")
# shellcheck disable=SC2312
active_day=$(basename "$(readlink "${file}")")
today=$(date -I)

if [ "${active_day}" != "${today}" ] && [ "${command}" != "day" ]; then
  echo "looking at ${active_day}; run 'to day' to update" >&2
fi
# shellcheck disable=SC2249
case "${command}"
in "cat")
     if [ $# -gt 0 ]; then
       cat "$@" | pretty
     else
       pretty <"${file}"
     fi
;; "do")
     if [ $# = 0 ]; then
       incomplete < "${file}" | pretty
     else
       new_task ' ' "${file}" "$@"
     fi
;; "dos")
     while read -r line; do
       new_task ' ' "${file}" "${line}"
     done
;; "done")
     if [ $# = 0 ]; then
       completed < "${file}" | pretty
     else
       new_task 'x' "${file}" "$@"
     fi
;; "dones")
     while read -r line; do
       new_task 'x' "${file}" "${line}"
     done
;; "day")
     if [ "${active_day}" = "${today}" ]; then
       echo "already up-to-date" >&2
       exit 1
     fi
     import "${active_day}" "${today}"
     # shellcheck disable=SC2312
     ln -sf "${today}" "$(get_file "today")"
;; "did")
     incomplete <"${file}" | sed 's/^- //' | fzf --multi --exact "--query=$*"
;; "edit")
     if [ $# = 0 ]; then
       ${VISUAL-} "${file}"
     else
       # shellcheck disable=SC2312
       ${VISUAL-} "$(get_file "$1")"
     fi
esac
