#!/bin/sh -e
#
# deps: todo.sh

os=$(uname -s | tr '[:upper:]' '[:lower:]')

if echo "$1" | grep -qE '^[0-9][0-9]*$' && [ -z "$2" ]; then
  if [ "${os}" = "linux" ]; then
    prevwindowname="$(ydotool getactivewindow getwindowname)"
  fi

  [ -n "$1" ] \
    && todo.sh do "$1" \
    | grep -E -o "https?://[^ ]*" \
      | sort -u | xargs -I{} open '{}'

  # shellcheck disable=SC2312
  if [ "${os}" = "linux" ]; then
    [ "$(ydotool getactivewindow getwindowname)" = "${prevwindowname}" ] \
      || i3-msg scratchpad show >/dev/null
  else
    # flip back to previous application
    osascript -e 'tell application "System Events" to keystroke tab using {command down}'
  fi
elif [ -n "$1" ]; then
  todo.sh "$*"
fi

clear -x
todo.sh list | head -n -2 | sort -k1n
