#!/bin/sh

# shellcheck disable=SC2250

. color.sh

ED="$(test -n $EDITOR && echo "$EDITOR" || echo "/usr/bin/vi")"

find_traf_dir() {
  res="$(pwd)"

  while [ ! -d "$res/.traf" ]; do
    if [ "$res" = "/" ]; then
      echo "Could not find a .traf directory here or in any parent directory" 1>&2
      exit 1
    fi
    res="$(dirname "$res")"
  done

  res="$res/.traf"
  printf "$res\n"
}

traf_new_idx() {
  DIR="$1"
  MAX="$(find "$DIR/todo" "$DIR/wip" "$DIR/done" -type f -exec basename {} \; | sort -n | tail -n 1)"
  printf "%d\n" $((MAX + 1))
}

traf_git_exists() {
  git --git-dir="$1/.git" status >/dev/null 2>&1
}

traf_add() {
  DIR="$(find_traf_dir)"
  test -z "$DIR" && exit 1

  NEW="$(traf_new_idx "$DIR")"
  test -z "$NEW" && exit 1

  if [ -n "$1" ]; then
    printf "$1\n" >"$DIR/todo/$NEW"
    summary="$1"
  else
    $ED "$DIR/todo/$NEW"
    summary="$(head -n 1 "$DIR/todo/$NEW")"
  fi
  if traf_git_exists "$DIR"; then
    git -C "$DIR" add "$DIR/todo/$NEW"
    git -C "$DIR" commit -m "new entry: $NEW" -m "task summary: $summary"
  fi
}

get_entries() {
  l="$(find "$1/$2" -type f)"
  reset="$(reset_fg)"
  for i in $l; do
    CATEGORY="$(echo "$2" | tr [a-z] [A-Z])"
    printf "%s $3$CATEGORY$reset   \t%s\n" "$i" "$(head -n 1 "$i")"
  done
}

traf_mv() {
  ENTRY1="${1##*/}"
  BASE1="${1%/*}"
  CAT1="${BASE1##*/}"
  ENTRY2="${2##*/}"
  BASE2="${2%/*}"
  CAT2="${BASE2##*/}"
  DIR="${BASE1%/*}"
  summary="$(head -n 1 "$1")"

  mv "$1" "$2"
  if traf_git_exists "$DIR"; then
    git -C "$DIR" add "$1" "$2"
    git -C "$DIR" commit -m "switch entry $ENTRY1 from $CAT1 to $CAT2" \
      -m "task summary: $summary"
  fi
}

traf_ed() {
  ENTRY="${1##*/}"
  DIR="${1%/*}"
  DIR="${DIR%/*}"

  $ED "$1"
  summary="$(head -n 1 "$1")"
  if traf_git_exists "$DIR"; then
    git -C "$DIR" add "$1"
    git -C "$DIR" commit -m "edit entry $ENTRY" \
      -m "task summary: $summary"
  fi
}

traf_rm() {
  ENTRY="${1##*/}"
  DIR="${1%/*}"
  DIR="${DIR%/*}"
  summary="$(head -n 1 "$1")"

  rm "$1"
  if traf_git_exists "$DIR"; then
    git -C "$DIR" add "$1"
    git -C "$DIR" commit -m "delete entry $ENTRY" \
      -m "task summary: $summary"
  fi
}

open_entry() {
  ENTRY="${1##*/}"
  BASE="${1%/*}"
  CATEGORY="${BASE##*/}"
  DIR="${BASE%/*}"

  set_bold
  set_fg 3
  cat "$1"
  reset_fg
  reset_bold
  while true; do
    printf "[t] TODO | [w] WIP | [d] DONE | [e] edit entry | [r] remove entry | [b] back | [q] quit\n"
    read -r res
    case "$res" in
      t)
        traf_mv "$1" "$DIR/todo/$ENTRY"
        return 0
        ;;
      w)
        traf_mv "$1" "$DIR/wip/$ENTRY"
        return 0
        ;;
      d)
        traf_mv "$1" "$DIR/done/$ENTRY"
        return 0
        ;;
      e)
        traf_ed "$1"
        return 0
        ;;
      r)
        traf_rm "$1"
        return 0
        ;;
      b) return 0 ;;
      q) return 1 ;;
      *) printf "Invalid input\n" 1>&2 ;;
    esac
  done
}

traf_get_local_entries() {
  TODO="$(get_entries "$1" "todo" "$(set_fg 1)")"
  test -n "$TODO" && TODO="$TODO\n"
  WIP="$(get_entries "$1" "wip" "$(set_fg 3)")"
  test -n "$WIP" && WIP="$WIP\n"
  DONE="$(get_entries "$1" "done" "$(set_fg 2)")"
  printf "$TODO$WIP$DONE"
}

traf_browse_local_entries() {
  DIR="$(find_traf_dir)"
  test -z "$DIR" && exit 1

  while true; do
    SEL="$(traf_get_local_entries "$DIR" | choice)"
    test -z "$SEL" && exit 0
    open_entry "$SEL" || return 0
  done
}

traf_get_global_entries() {
  blue="$(set_fg "${COLOR_BLUE}")"
  bold="$(set_bold)"
  reset="$(reset_fg)$(reset_bold)"
  while read -r project; do
    base="${project%/*}"
    name="${base##*/}"
    cur="$(traf_get_local_entries "$project")"
    test -n "$cur" && cur="$cur\n"
    printf '%b' "$cur" | sed -e "s/\(^[^ ]* \)/\1${blue}${bold}[$name]${reset}    \t/g"
  done <"$HOME/.trafprojs"
}

traf_browse_global_entries() {
  while true; do
    SEL="$(traf_get_global_entries | choice)"
    test -z "$SEL" && exit 0
    open_entry "$SEL" || return 0
  done
}

traf_all_git() {
  while read -r project; do
    set_fg "$COLOR_BLUE"
    set_bold
    printf '%b' "[$project]\n"
    reset_fg
    reset_bold
    if traf_git_exists "$project"; then
      git -C "$project" "$@"
    else
      printf "nogit\n"
    fi
  done <"$HOME/.trafprojs"
}

print_help() {
  printf "traf [init | todo [<task summary>] | all | git]\n"
  printf "    init [repo_url]: init traff in the current directory. If a repo URL is given, it will clone it into .traf\n"
  printf "    todo [<task_name>]: add a todo task, if no argument supplied, open the \$EDITOR (or vi if variable empty) to write a detailed task\n"
  printf "    all: display all tasks in all projects referenced in \$HOME/.traff"
  printf "    git: execute git command in .traf repository"
}

case "$1" in
  init)
    shift
    if [ -n "$1" ]; then
      git clone "$1" ".traf" || exit 1
    fi
    mkdir -p .traf || exit 1
    for i in todo wip done; do
      mkdir -p ".traf/$i" || exit 1
    done
    find_traf_dir >>"$HOME/.trafprojs"
    ;;
  todo)
    shift
    traf_add "$1"
    ;;
  all)
    shift
    case "$1" in
      git)
        shift
        traf_all_git "$@"
        ;;
      "")
        traf_browse_global_entries
        ;;
      *)
        print_help
        ;;
    esac
    ;;
  git)
    DIR="$(find_traf_dir)"
    shift
    git -C "$DIR" --git-dir="$DIR/.git" "$@"
    ;;
  "")
    traf_browse_local_entries
    ;;
  *)
    print_help
    exit 1
    ;;
esac
