#!/bin/zsh -f
# vim: ft=zsh:
# MIT License
# For my own and others sanity
# git:
# %b => current branch
# %a => current action (rebase/merge)
# prompt:
# %F => color dict
# %f => reset color
# %~ => current path
# %* => time
# %n => username
# %m => shortname host
# %(?..) => prompt conditional - %(condition.true.false)

# turns seconds into human readable time
# 165392 => 1d 21h 56m 32s
prompt_pure_human_time() {
	local tmp=$1
	local days=$(( tmp / 60 / 60 / 24 ))
	local hours=$(( tmp / 60 / 60 % 24 ))
	local minutes=$(( tmp / 60 % 60 ))
	local seconds=$(( tmp % 60 ))
	(( $days > 0 )) && echo -n "${days}d "
	(( $hours > 0 )) && echo -n "${hours}h "
	(( $minutes > 0 )) && echo -n "${minutes}m "
	echo "${seconds}s"
}

is_git_repo() {
	command git rev-parse --is-inside-work-tree &>/dev/null
	return $?
}

# fastest possible way to check if repo is dirty
prompt_pure_git_dirty() {
	# check if we're in a git repo
	is_git_repo || return
	# check if it's dirty
	[[ "$PURE_GIT_UNTRACKED_DIRTY" == 0 ]] && local umode="-uno" || local umode="-unormal"
	command test -n "$(git status --porcelain --ignore-submodules ${umode})"

	(($? == 0)) && echo '*'
}

prompt_pure_git_wip() {
	is_git_repo || return
	local subject="$(command git show --pretty=%s --quiet HEAD 2>/dev/null)"
	[ "$subject" == 'wip' ] && echo '[WIP]'
}

# displays the exec time of the last command if set threshold was exceeded
prompt_pure_cmd_exec_time() {
	local stop=$EPOCHSECONDS
	local start=${cmd_timestamp:-$stop}
	integer elapsed=$stop-$start
	(($elapsed > ${PURE_CMD_MAX_EXEC_TIME:=5})) && prompt_pure_human_time $elapsed
}

prompt_pure_preexec() {
	cmd_timestamp=$EPOCHSECONDS

	# shows the current dir and executed command in the title when a process is active
	print -Pn "\e]0;"
	echo -nE "$PWD:t: $2"
	print -Pn "\a"
}

# string length ignoring ansi escapes
prompt_pure_string_length() {
	echo ${#${(S%%)1//(\%([KF1]|)\{*\}|\%[Bbkf])}}
}

prompt_pure_nix_info() {
	local packages_info=''
	if [[ -z $NIX_SHELL_PACKAGES ]]; then
		packages_info='[nix-shell]'
	else
		packages_info="{ $NIX_SHELL_PACKAGES }"
	fi

	case $IN_NIX_SHELL in
		'pure')
			echo "$fg_bold[green][nix-shell] "
			;;
		'impure')
			echo "$fg_bold[magenta][nix-shell] "
			;;
		*) ;;
	esac
}

prompt_pure_precmd() {
	if [[ "$TERM" == "dumb" ]]; then
		return
	fi

	# shows the full path in the title
	print -Pn '\e]0;%~\a'

	# git info
	vcs_info

	local prompt_pure_preprompt="\n$(prompt_pure_nix_info)$fg_bold[green]$prompt_pure_username%F{blue}%~%F{yellow}$vcs_info_msg_0_`prompt_pure_git_dirty` $fg_no_bold[red]`prompt_pure_git_wip`%f %F{yellow}`prompt_pure_cmd_exec_time`%f "
	print -P $prompt_pure_preprompt

	# check async if there is anything to pull
	# (( ${PURE_GIT_PULL:-1} )) && {
	# 	# check if we're in a git repo
	# 	command git rev-parse --is-inside-work-tree &>/dev/null &&
	# 	# make sure working tree is not $HOME
	# 	[[ "$(command git rev-parse --show-toplevel)" != "$HOME" ]] &&
	# 	# check check if there is anything to pull
	# 	command git fetch &>/dev/null &&
	# 	# check if there is an upstream configured for this branch
	# 	command git rev-parse --abbrev-ref @'{u}' &>/dev/null && {
	# 		local arrows=''
	# 		(( $(command git rev-list --right-only --count HEAD...@'{u}' 2>/dev/null) > 0 )) && arrows='⇣'
	# 		(( $(command git rev-list --left-only --count HEAD...@'{u}' 2>/dev/null) > 0 )) && arrows+='⇡'
	# 		print -Pn "\e7\e[A\e[1G\e[`prompt_pure_string_length $prompt_pure_preprompt`C%F{cyan}${arrows}%f\e8"
	# 	}
	# } &!

	# reset value since `preexec` isn't always triggered
	unset cmd_timestamp
}


prompt_pure_setup() {
	# prevent percentage showing up
	# if output doesn't end with a newline
	export PROMPT_EOL_MARK=''

	prompt_opts=(cr subst percent)

	zmodload zsh/datetime
	autoload -Uz add-zsh-hook
	autoload -Uz vcs_info

	add-zsh-hook precmd prompt_pure_precmd
	add-zsh-hook preexec prompt_pure_preexec

	zstyle ':vcs_info:*' enable git
	zstyle ':vcs_info:git*' formats ' %b'
	zstyle ':vcs_info:git*' actionformats ' %b|%a'

	# show username@host if logged in through SSH
	[[ "$SSH_CONNECTION" != '' ]] && prompt_pure_username='%n@%m '

	# prompt turns red if the previous command didn't exit with 0
	PROMPT='%(?.%F{green}.%F{red})❯%f '
}

prompt_pure_setup "$@"
