# Magic prompt with colors
# username in blue if not root
# username in red if root - time in pink w/
# DANGER replacing the date
# failed jobs print exit status in the RPS1 with yellow text
setopt prompt_subst

preexec () {
        currJob="`echo $3 | cut -d ' ' -f 1 | head -n 1`"
        if [[ "$TERM" == "screen" ]]; then
                hostUser="%10<...<%~%<<"
                print -Pn "\ek[$hostUser $currJob]\e\\"
        else
                if [[ "$FANCYTYPE" == "YES" ]]; then
                        hostUser="%n@%m: %2~"
                        print -Pn "\e]0;$hostUser [$currJob]\a"
                fi
        fi
}

PROMPT_TMP="${HOME}/.augie-zsh-tmp-prompt"

function right_side_prompt() {
    cd $1
    branch=`vcs_current_branch`
    if [ $? = 0 ] ; then
        print $branch
    fi
}

function _init_async() {
    async
    async_stop_worker 'durin42_prompt' || true
    async_start_worker durin42_prompt -u -n
    async_register_callback durin42_prompt right_prompt_results
}

function right_prompt_results() {
    if [ $2 = 0 ] ; then
        rps_branch=$3
        zle && zle reset-prompt
     else
         _init_async
     fi
}

if [ "x`whoami`" = "xroot" ] ; then
        PS1=$'%{\e];%n@%m: %2~ [zsh]\a%}[%m:%3~] %{\e[31m%}%n%{\e[0m%}%# '
        if [[ "$TERM" == "screen" ]] ; then
                PS1=$'%{\ek[%2~ zsh]\e\\%}[%m:%3~] %{\e[31m%}%n%{\e[0m%}%# '
        fi
        RPS1=$'%{\e[1;35m%}[DANGER %t]%{\e[0m%}%(?..%{\e[1;33m%} %?%{\e[1;0m%})'
else
        PS1=$'%{\e];%n@%m: %2~ [zsh]\a%}[%m:%3~] %{\e[34m%}%n%{\e[0m%}%# '
        if [[ "$TERM" == "screen" ]]; then
                PS1=$'%{\ek[%2~ zsh]\e\\%}[%m:%3~] %{\e[34m%}%n%{\e[0m%}%# '
        fi
    RPS1=$'[$rps_branch]%(?..%{\e[1;33m%} %?%{\e[0m%})'
fi


export FANCYTYPE="NO"

for ok in rxvt rxvt-unicode xterm xterm-256color xterm-color screen ; do
    if [ "$TERM" = "$ok" ] ; then
        export FANCYTYPE="YES"
    fi
done

if [ $FANCYTYPE = "NO" ] ; then
    prompt='[%m:%3~] %n%# '
    RPS1=$'[%W %t]'
fi

if [[ $TERM == "dumb" ]]; then  # in emacs
    # for tramp to not hang, need the following. cf:
    # http://www.emacswiki.org/emacs/TrampMode
    unsetopt zle
    unsetopt prompt_cr
    unsetopt prompt_subst
    unfunction preexec
    PS1='$ '
    RPS1=''
else
    autoload -Uz async
    _init_async
    function precmd () {
        rps_branch="$(date '+%D %H:%M')"
        async_job durin42_prompt right_side_prompt $PWD
    }
fi


#nonfancy no-frills prompt - disabled (same as the "non-fancy" one above)
#prompt='[%m:%3~] %n%# '
#RPS1=$'[%W %t]'
