# -*- shell-script -*-

################################################################################

bashrun_progress_percent=0
bashrun_progress_active=0
bashrun_progress_task="Busy"
bashrun_progress_line=""

function §progress.enabled? {
    [[ bashrun_debug -eq 0 && bashrun_feedback -eq 1 && §window.terminal? ]]
}

§progress.new () {
    bashrun_progress_task="${1:-Progress}"
    bashrun_progress_percent="${2:-0}"
    bashrun_progress_active=1

    §progress.update "$bashrun_progress_percent"

    if §progress.enabled?; then
	tput civis >&2
    fi
}

§progress.update () {

    local value="$1"
    if [[ "${value:0:1}" == "+" ]]; then
	((bashrun_progress_percent+=${value:1}))
    else
	bashrun_progress_percent="$value"
    fi

    if (( bashrun_progress_percent > 100 )); then
	bashrun_progress_percent=100
    fi

    if (( $# == 2 )); then
	bashrun_progress_task="$2"
    fi
    §progress.update_line
    §progress.draw
}

§progress.update_line () {

    local i=0
    declare -i spaces=$(( 
	    $COLUMNS - ${#bashrun_progress_task} - 
	    ${#bashrun_progress_percent} - 4 
	    ))

    bashrun_progress_line="$bashrun_progress_task"
    for ((i=0; i<spaces; i++)); do
	bashrun_progress_line+=" "
    done
    bashrun_progress_line+=" [$bashrun_progress_percent%]"
}

§progress.draw () {

    §progress.enabled? || return 1

    declare -i len=$(( COLUMNS * bashrun_progress_percent / 100 ))

    tput el 
    tput cr 

    printf '%b' '\e[7m' >&2
    printf '%s' "${bashrun_progress_line:0:len}" >&2
    printf '%b' '\e[0m' >&2
    printf '%s' "${bashrun_progress_line:len}" >&2
}
    
§progress.reset () {

    bashrun_progress_percent=0
    bashrun_progress_task="Busy"
    bashrun_progress_active=0

    if §progress.enabled?; then
	tput cnorm >&2
	tput cr >&2
	tput el >&2
	tput cr >&2
    fi
}

