#!/bin/zsh

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


# Background changes depending on solarized theme
case ${SOLARIZED_THEME:-dark} in
    light) local bkg=white;;
    *)     local bkg=black;;
esac

local ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg_bold[green]%}[%{$fg_bold[blue]%}"
local ZSH_THEME_GIT_PROMPT_SUFFIX="%{$fg_bold[green]%}]"
local ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg_no_bold[green]%}✓"
local ZSH_THEME_GIT_PROMPT_AHEAD="%{$fg_no_bold[cyan]%}▴"
local ZSH_THEME_GIT_PROMPT_BEHIND="%{$fg_no_bold[magenta]%}▾"
local ZSH_THEME_GIT_PROMPT_STAGED="%{$fg_no_bold[green]%}●"
local ZSH_THEME_GIT_PROMPT_UNSTAGED="%{$fg_no_bold[yellow]%}●"
local ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg_no_bold[red]%}●"

local ZSH_THEME_VIRTUALENV_PREFIX=" %{$fg_bold[green]%}(%{%b$fg[green]%}"
local ZSH_THEME_VIRTUALENV_SUFFIX="%{$reset_color$fg_bold[green]%})%{$reset_color%}"

# Depending if root or not, displays the right prompt char
# and changes the color of the username
if [[ $EUID -eq 0 ]]; then
  local _USERNAME="%{$fg_bold[red]%}%n"
  local _LIBERTY="%{$fg_no_bold[red]%}#"
else
  local _USERNAME="%{$fg_bold[green]%}%n"
  local _LIBERTY="%{$fg_no_bold[green]%}$"
fi
_LIBERTY="$_LIBERTY%{$reset_color%}"


function virtualenv_prompt_info(){
    [[ -n ${VIRTUAL_ENV} ]] || return
    echo "${ZSH_THEME_VIRTUALENV_PREFIX:=[}${VIRTUAL_ENV:t}${ZSH_THEME_VIRTUALENV_SUFFIX:=]}"
}

# disables prompt mangling in virtual_env/bin/activate
export VIRTUAL_ENV_DISABLE_PROMPT=1

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

    local _VENV_PROMPT="%{%}$(virtualenv_prompt_info)"

    echo "$_GIT_CHAR$_VENV_PROMPT $_LIBERTY"
}

function 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%}
}

space_sh_git_branch () {
    local ref=$(command git symbolic-ref HEAD 2> /dev/null) || \
        ref=$(command git rev-parse --short HEAD 2> /dev/null) || return
    echo "${ref#refs/heads/}"
}

space_sh_git_status () {
    _INDEX=$(command git status --porcelain -b 2> /dev/null)
    local _STATUS=""
    if $(echo "$_INDEX" | grep '^[AMRD]. ' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_STAGED"
    fi
    if $(echo "$_INDEX" | grep '^.[MTD] ' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_UNSTAGED"
    fi
    if $(echo "$_INDEX" | command grep -E '^\?\? ' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_UNTRACKED"
    fi
    if $(echo "$_INDEX" | grep '^UU ' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_UNMERGED"
    fi
    if $(command git rev-parse --verify refs/stash >/dev/null 2>&1); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_STASHED"
    fi
    if $(echo "$_INDEX" | grep '^## .*ahead' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_AHEAD"
    elif $(echo "$_INDEX" | grep '^## .*behind' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_BEHIND"
    fi
    if $(echo "$_INDEX" | grep '^## .*diverged' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_DIVERGED"
    fi

    echo $_STATUS
}

space_sh_git_prompt () {
    local _branch=$(space_sh_git_branch)
    local _result=""
    if [[ "${_branch}x" != "x" ]]; then
        local _status=$(space_sh_git_status)
        _result="$ZSH_THEME_GIT_PROMPT_PREFIX$_branch"
        if [[ "${_status}x" != "x" ]]; then
            _result="$_result $_status"
        fi
        _result="$_result$ZSH_THEME_GIT_PROMPT_SUFFIX"
    fi
    echo $_result
}

################################################################################
# Prompt display                                                               #
################################################################################

prompt_msg () {
    case $(cat /dev/shm/prompt_msg) in
        update_rc)
            msg="Update ready for rc";;
        git_unpushed)
            msg="You have unpushed business in $HOME/rc";;
        git_network_unreachable)
            msg="Can\'t reach rc git repo";;
        update_sys)
            msg="Update ready for system";;
        *)
            msg="";;
    esac

    echo $msg
}

prompt_create () {
    # Carriage return to give the prompt some air
    PROMPT="%{$reset_color%}"$'\n'

    # Username, red when logged as root
    PROMPT+='$_USERNAME'

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

    # Hostname, colors defined just above
    PROMPT+="%{$fg_bold[$couleur_hote]%}"'%m'

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

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

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

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

    # Right prompt with current repo informations
    RPROMPT='$(space_sh_git_prompt)'"%E%{$reset_color%}"

    #PROMPT="$Heure $Utilisateur@$Machine %{$fg_no_bold[yellow]%}%~
    #%{$reset_color%}%# "
    #RPROMPT="\$(charge_batterie) %(!,%B[%?]%b,[%?])"

    #RPROMPT="${vcs_info_msg_0_} \$(charge_batterie) %(!,%B[%?]%b,[%?])"

    #RPROMPT=" %(!,%B[%?]%b,[%?])"

    # %{  %} pas d'affichage, à utiliser pour ne pas fausser le calcul de RPROMPT
    # $fg[color], $fg_(no_)bold[color], $reset_color
    # black red green yellow blue magenta cyan white

    eval PROMPT='$PROMPT'
    eval RPROMPT='$RPROMPT'
}

################################################################################
# Mise à jour automatique à partir du repo distant                             #
################################################################################
#
update_config () {
    # Get rc dir path
    RC_PATH=$(dirname "$(readlink -f ${(%):-%x})")

    CUR_DIR=`pwd`
    cd $RC_PATH

    # In case the network is down, don't lock the terminal
    timeout 6 git fetch > /dev/null 2>&1
    #
    # Timeout returns 124 on timeout
    if [ "$?" -ge "124" ]; then
        echo 'git_network_unreachable' > /dev/shm/prompt_msg
    fi

    # Check if the repo is clean
    git_st=$(command git status --porcelain -b 2> /dev/null)
    if $(echo "$git_st" | grep '^## .*ahead' &> /dev/null); then
        echo 'git_unpushed' > /dev/shm/prompt_msg
    elif $(echo "$git_st" | grep '^## .*behind' &> /dev/null); then
        echo 'update_rc' > /dev/shm/prompt_msg
    fi

    cd $CUR_DIR
}


#git pull --rebase --stat origin master
#$RC_PATH/install.sh
#cd $CUR_DIR
#source $HOME/.zshrc