#!/usr/bin/env bash

calindx="$HOME/.local/share/calcurse/.env"
todoitems=$(calcurse --todo=1 --format-todo="%m\n"| tail -n +2 )
readarray -t todolist <<<$todoitems

# get index
if [[ ! -f "$calindx" ]] ; then
    echo "INDEX=0" > "$calindx"
fi

source "$calindx"

# increment
if [[ "$1" == "inc" ]] ; then
    ((INDEX+=1))
elif [[ "$1" == "dec" ]] ; then
    ((INDEX-=1))
fi

# perform checks on the index. Adjusts to dynamic lists
if [[ $INDEX -ge ${#todolist[@]} ]] ; then
    INDEX=0 # loops
elif [[ $INDEX -lt 0 ]] ; then
    INDEX=$((${#todolist[@]}-1))
fi

# saves index
echo "INDEX=$INDEX" > "$calindx"
printf '%s (%d/%d)\n' "${todolist[$INDEX]}" $(($INDEX+1)) ${#todolist[@]}
