# vim: setf zsh

# Allow color escape sequences to be available
autoload -U colors && colors

# Initialize VCS prompt configuration
autoload -Uz vcs_info

# And the hooks system
autoload -Uz add-zsh-hook

zstyle ':vcs_info:*' enable git svn
zstyle ':vcs_info:*' check-for-changes true
zstyle ':vcs_info:*' check-for-staged-changes true
zstyle ':vcs_info:*' actionformats \
    '%F{5}(%f%s@%r%F{5})%F{3} - %F{5}[%F{2}%u%b%c%F{3}|%F{1}%a%F{5}]%f'
zstyle ':vcs_info:*' formats       \
    '%F{5}(%f%s@%r%F{5})%F{3} - %F{5}[%F{2}%u%b%c%F{5}]%f'
zstyle ':vcs_info:(sv[nk]|bzr):*' branchformat '%b%F{1}:%F{3}%r'
zstyle ':vcs_info:*' unstagedstr '~'
zstyle ':vcs_info:*' stagedstr   '±'


# Allow calling functions inside prompt
setopt PROMPT_SUBST

PROMPT_VENV_INDICATOR="🐍"

if [[ $(echo $PROMPT_VENV_INDICATOR | wc -L) -ne 2 ]]; then
	# Workaround for older systems
	PROMPT_VENV_INDICATOR="p:"
fi

function prompt_last_cmd() {
	if [[ $HISTCMD -gt 0 ]]; then
		echo $history[$((HISTCMD - 1))]
	fi
}

function prompt_handle_virtualenv() {
	if [[ -n $VIRTUAL_ENV ]]; then
		echo "%{$fg_bold[green]%}%S$PROMPT_VENV_INDICATOR%s $(basename $VIRTUAL_ENV)%b%f%k "
	fi
}

function prompt_ps1() {
	local ps1 rs='%b%f%k%s'
    local dir="%{$fg[%~]%}%8~$rs"
	local hist="%{$fg[blue]%}%(?..%S)[\$(prompt_last_cmd)]$rs "
	local host="%{$fg[red]%}%m$rs "
	# Highlight the hostname if we are connected over SSH
	if [[ -n $SSH_TTY ]]; then
		host="%S%B$host"
	fi

	local shlvl="%{$fg[black]%}%{$bg[magenta]%}\${(l:$SHLVL-1::>:)}%{$reset_color%}"
	local prompt="%n@%{$fg[cyan]%}%m$rs %# "
	ps1=(
		"$host"
		"$hist"
		"$dir"
		$'\n'
		'$(prompt_handle_virtualenv)'
		'${vcs_info_msg_0_:+${vcs_info_msg_0_}\n}'
		"$shlvl"
		"$prompt"
	)
    echo "${(j::)ps1}"
}

function prompt_rprompt() {
	local rprompt rs='%b%f%k' hist1 hist2
	local exit_status="%(?..%{$fg[red]%}- %{$fg_bold[yellow]%}%? %b%{$fg[red]%}-$rs )"
	local datetime="%D %{$fg[red]%}%T%{$reset_color%}"
	rprompt=(
		"$exit_status"
		"$datetime"
	)
    echo "${(j::)rprompt}"
}

function prompt_precmd () {
	# Set window title to username@machine: pwd
	print -Pn "\e]0;%n@%m: %2~\a"
	# Load VCS info
	vcs_info
}

function prompt_preexec () {
	# Set window title to command about to be executed.
	if [[ -n $1 ]]; then
		print -Pn "\e]0;$1\a"
	fi
}

add-zsh-hook precmd prompt_precmd
add-zsh-hook preexec prompt_preexec

PS1="$(prompt_ps1)"
RPROMPT="$(prompt_rprompt)"

# We handle virtualenv ourselves, no need to do it twice.
export VIRTUAL_ENV_DISABLE_PROMPT=1
