################################################################################
# Utility functions for the prompt                                             #
################################################################################

# Depending if root or not, displays the right prompt char
# and changes the color of the username
color_username () {
    if [[ $EUID -eq 0 ]]; then
        echo "%{$fg_bold[red]%}%n"
    else
        echo "%{$fg_bold[green]%}%n"
    fi
}

color_prompt_char () {
    if [[ $EUID -eq 0 ]]; then
        echo "%{$fg_no_bold[red]%}#%{$reset_color%}"
    else
        echo "%{$fg_no_bold[green]%}$%{$reset_color%}"
    fi
}

# Host coloring, specific to Rezometz
color_host () {
    local couleur_hote=""
    case $HOST in
        TwelveYearsAndStillGoingStrong|lharkinateur|BecauseROSThatSWhy|lharktop|blieuxor)
            couleur_hote=cyan;;
        chimay|orval)
            couleur_hote=magenta;;
        babel|taima|era|vidar|okami|athena)
            couleur_hote=red;;
        loki|skadi)
            couleur_hote=blue;;
        *)
            couleur_hote=white;;
    esac
    echo "%{$fg_bold[$couleur_hote]%}%m"
}

last_status () {
    echo "%(?..%{$fg_no_bold[red]%}[%?])"
}

virtual_env() {
    local prefix="%{$fg_bold[green]%}(%{%b$fg[green]%}"
    local suffix="%{$reset_color$fg_bold[green]%})%{$reset_color%}"
    [[ -n ${VIRTUAL_ENV} ]] || return
    printf '%s' "${prefix}${VIRTUAL_ENV:t}${suffix}"
}

prompt_chars() {
    local git_char=''
    if $(git rev-parse --is-inside-work-tree >/dev/null 2>&1); then
        local git_char="%{$fg_no_bold[blue]%}±%{$reset_color%}"
    fi
    printf '%s' "${_GIT_CHAR}$(last_status) $(color_prompt_char)"
}

charge_batterie() {
    local BATTERY=/sys/class/power_supply/BAT0
    local REM_CAP=`cat $BATTERY/charge_now`
    local FULL_CAP=`cat $BATTERY/charge_full`
    local BATSTATE=`cat $BATTERY/status`
    local CHARGE=$(( $REM_CAP * 100 / $FULL_CAP ))
    local Batterie=""
    case $BATSTATE in
        'Full')
            Batterie="~";;
        'Charging')
            Batterie="+";;
        'Discharging')
            Batterie="-";;
    esac
    # Maximum à 100%
    if [ $CHARGE -gt "99" ]
    then
        CHARGE=100
    fi
    local Couleur="magenta"
    if [ $CHARGE -gt "15" ]
    then
        Couleur="yellow"
    fi
    if [ $CHARGE -gt "30" ]
    then
        Couleur="green"
    fi

    echo %{$fg[${Couleur}]%B%}${Batterie}%{%b$fg[${Couleur_batt}]%}$CHARGE%%%{$reset_color%}
}

prompt_msg () {
    # TODO clean up /dev/shm when prompt_msg not in use
    # TODO Use unique filename in case multiple people use the same prompt
    line=$(tail -1 /dev/shm/prompt_msg) 2> /dev/null
    case $line in
        update_rc)
            msg="Update ready for rc. Run uprc to proceed";;
        git_unpushed)
            msg="You have unpushed business in $HOME/rc";;
        git_network_unreachable)
            msg="Can't reach rc git repo";;
        update_sys*)
            nb_pkg=$(printf '%s' "$line" | grep -o '[0-9]*' | head -n 1)
            msg="Update ready for the system. $nb_pkg new package$([ $nb_pkg -gt 1 ] && printf 's')";;
        *)
            msg="";;
    esac

    # Remove last message from stack before it drives us mad
    sed -i '$ d' /dev/shm/prompt_msg 2> /dev/null
    echo $msg
}

# Display vim mode while using zle line editing
# https://dougblack.io/words/zsh-vi-mode.html
vim_mode () {
    VIM_NORMAL="%{$fg_bold[red]%}[% N]% "
    VIM_INSERT="%{$fg_bold[green]%}[% I]% "
    VIM_PROMPT="${${KEYMAP/vicmd/$VIM_NORMAL}/(main|viins)/$VIM_INSERT}"
    echo "$VIM_PROMPT%{$reset_color%}"
}

# set formats
# %R - repository path
# %S - path in the repository
# %a - action (e.g. rebase-i)
# %b - branchname
# %c - stangedstr (see below)
# %i - The current revision number or identifier.
# %m - Misc. In case of Git, show information about stashes
# %r - The name of the root directory of the repository
# %s - The current version control system, like git or svn
# %u - unstagedstr (see below)
fmt_branch="%b%{$reset_color%} %u%c%m%{$reset_color%}" # e.g. master¹²
fmt_action="(%{$fg[red]%}%a%{$reset_color%})"   # e.g. (rebase-i)
fmt_pre="%{$fg_bold[blue]%}[%{$reset_color%}%{$fg[blue]%}"
fmt_post="%{$fg_bold[blue]%}]%{$reset_color%}"

# check-for-changes can be really slow.
# you should disable it, if you work with large repositories
zstyle ':vcs_info:*' enable git cvs svn
zstyle ':vcs_info:*' check-for-changes true
zstyle ':vcs_info:*' unstagedstr "%{$fg_no_bold[yellow]%}●"
zstyle ':vcs_info:*' stagedstr "%{$fg_no_bold[green]%}●"
zstyle ':vcs_info:*' actionformats "${fmt_pre}${fmt_branch}${fmt_action}${fmt_post} "
zstyle ':vcs_info:*' formats       "${fmt_pre}${fmt_branch}${fmt_post} "
zstyle ':vcs_info:*' nvcsformats   ""
zstyle ':vcs_info:*+*:*' debug false # Set to true to see which hooks are being run
zstyle ':vcs_info:git*+set-message:*' hooks git-st git-untracked

### git: Show marker red (●) if there are untracked files in repository
# Make sure you have added staged to your 'formats':  %c
+vi-git-untracked(){
    if [[ $(git rev-parse --is-inside-work-tree 2> /dev/null) == 'true' ]] && \
        git status --porcelain | grep '??' &> /dev/null ; then
        # This will show the marker if there are any untracked files in repo.
        # If instead you want to show the marker only if there are untracked
        # files in $PWD, use:
        #[[ -n $(git ls-files --others --exclude-standard) ]] ; then
        hook_com[unstaged]="%{$fg_no_bold[red]%}●%{$reset_color%}"$hook_com[unstaged]
    fi
}

### git: Show ▴/▾ when your local branch is ahead-of or behind remote HEAD.
# Make sure you have added misc to your 'formats':  %m
+vi-git-st() {
    local ahead behind gitstatus

    # for git prior to 1.7
    # ahead=$(git rev-list origin/${hook_com[branch]}..HEAD | wc -l)
    ahead=$(git rev-list ${hook_com[branch]}@{upstream}..HEAD 2>/dev/null | wc -l)
    (( $ahead )) && gitstatus+="%{$fg_no_bold[cyan]%}▴%{$reset_color%}"

    # for git prior to 1.7
    # behind=$(git rev-list HEAD..origin/${hook_com[branch]} | wc -l)
    behind=$(git rev-list HEAD..${hook_com[branch]}@{upstream} 2>/dev/null | wc -l)
    (( $behind )) && gitstatus+="%{$fg_no_bold[magenta]%}▾%{$reset_color%}"

    hook_com[misc]+=${gitstatus}
}


precmd() { vcs_info }

prompt_create zle-line-init zle-keymap-select () {
    # Carriage return to give the prompt some air
    PROMPT="%{$reset_color%}"$'\n'

    # Username, red when logged as root
    PROMPT+="$(vim_mode) $(color_username)"

    # @ symbol
    PROMPT+="%{$fg_bold[blue]%}@"

    # Hostname, colors defined just above
    PROMPT+="$(color_host)"

    # White space to separate host from pwd
    PROMPT+=" %{$reset_color%}"

    # Current working directory, use ~ when needed
    PROMPT+="%{$fg[yellow]%}"'%~'

    # Display current message
    PROMPT+="%{$fg[red]%} $(prompt_msg)"

    # Change the background for the whole line and line feed
    PROMPT+="%{$fg_bold[green]%}%E"$'\n'

    # Prompt characters for virtualenv, git and zsh
    PROMPT+="$(virtual_env)$(prompt_chars) %{$reset_color%}"

    # Right prompt with current repo informations
    RPROMPT="${vcs_info_msg_0_}%E%{$reset_color%}"

    zle reset-prompt
}

# vim: ft=zsh