#!/bin/bash
# @desc Small pomodoro timer in bash. Should be run in tmux session.
SCRIPTDIR=$(dirname $(readlink -f $0))
eprintf(){
    printf "$@" >&2
}
datefmt(){
    date -d@"$1" +%H:%M:%S
}
datediff(){
    date -ud@"$(($1-$2))" +%H:%M:%S
}
setstatus(){
    eprintf "%s\n" "$1"
    notify-send "$1"
    bash $SCRIPTDIR/telegram.sh "$1"
}
timer_wait(){
    TIME_START="$(date +%s)"
    REAL_START=$TIME_START
    TIME_END=$(( $(date +%s) + $1 ))
    sp='/-\|'
    i=1
    while [ $(date +%s) -lt $TIME_END ]  || [ ${PAUSE:-0} -gt 0 ]
    do
        TIME_NOW=$(date +%s)
        PERCENT=$(( ( $TIME_NOW - $TIME_START ) * 100 / ($TIME_END - $TIME_START) ))
        [ ${PAUSE:-0} -eq 0 ]&& \
            eprintf "[%s-%s] %s %d%% %c\r" "$(datefmt $REAL_START)" "$(datefmt $TIME_END)" \
			"$(datediff $TIME_END $TIME_NOW)" "$PERCENT" "${sp:i++%${#sp}:1}"
        read -n 1 -t 1 -s action_ch
        case "$action_ch" in
            "b" | "B") break ;;
            "s" | "S" | "q" | "Q" ) exit 0;;
            "p") 
                if [ "${PAUSE:-0}" -gt 0 ]
                then
                    DELTA=$(( $(date +%s) - $PAUSE ))
                    PAUSE=0
                    TIME_START=$(($TIME_START +$DELTA))
                    TIME_END=$(( $TIME_END + $DELTA ))
                else
                    eprintf "\n[timer paused]\n"
                    PAUSE=$(date +%s)
                fi
            ;;
        esac
    done
    echo >&2

}
state_work(){
    setstatus "Work"
    mpc play >&2
    task >&2
    timer_wait $(( 25*60 ))
    mpc stop >&2
    if (( $BRKS % $BREAK_RATIO )) || ! (($BRKS))
    then
        echo state_short_break
    else 
        echo state_long_break
    fi
}
state_short_break(){
    setstatus "Short break"
    timer_wait $(( 5*60 )) 
    echo state_work
}
state_long_break(){
    setstatus "Long break"
    fortune >&2
    timer_wait $(( 15*60 ))
    echo state_work
}
STATE=state_work
BRKS=0
BREAK_RATIO=3
while [ -n "$STATE" ]
do
    if [[ $STATE =~ break ]]
    then 
        BRKS=$(( $BRKS + 1 ))
    fi
    STATE=`$STATE`
done
