# color stuff

# return contrasted color
contrastcol() {
  local bg=${1:-#000000}
  local dark=${2:-#2e3440}  # color if provided color is light
  local light=${3:-#eceff4} # color if provided color is dark
  local threshold=${4:-128}

  local r=$((16#${bg[2,3]})) # use arithmetic expansion to convert hex to decimal
  local g=$((16#${bg[4,5]}))
  local b=$((16#${bg[6,7]}))

  local brightness=$((0.2126*r + 0.7152*g + 0.0722*b)) # For rough calculations, the formula uses linear RGB values (0–255) with CIE-weighted coefficients | source: https://www.codestudy.net/blog/formula-to-determine-perceived-brightness-of-rgb-color
  if ((brightness > threshold)); then
    echo $dark
  else
    echo $light
fi
}

# set darktheme if between 18 and 6
DARK=false
if (($(date +%H) < 6 && $(date +%H) > 18)); then
  DARK=true
fi

# Run pywal automatically; can be forced just by putting a blank ".reset_color" in home directory
if ([ -f $XDG_CONFIG_HOME/wallpaper/current ] && [ ! -d $XDG_CACHE_HOME/wal ]) || [ -f $HOME/.reset_color ]; then
  wal --cols16 dual -n -e -s -t -p "current_theme" -i .config/wallpaper/current
  [ -f $HOME/.reset_color ] && rm $HOME/.reset_color
fi

# if pywal has been runned, get colors
if [ -f $XDG_CACHE_HOME/wal/colors ]; then
  BG1=$(sed '1q;d' $XDG_CACHE_HOME/wal/colors)
  BG2=$(sed '2q;d' $XDG_CACHE_HOME/wal/colors)
  BG3=$(sed '3q;d' $XDG_CACHE_HOME/wal/colors)
  BG4=$(sed '4q;d' $XDG_CACHE_HOME/wal/colors)
else
  BG1=#2e3440
  BG2=#3c4453
  BG3=#454d5f
  BG4=#4d576a
fi

FG1=$(contrastcol "$BG1")
FG2=$(contrastcol "$BG2")
FG3=$(contrastcol "$BG3")
FG4=$(contrastcol "$BG4")

# source global shell alias & variables files
[ -f "$XDG_CONFIG_HOME/shell/alias" ] && source "$XDG_CONFIG_HOME/shell/alias"
[ -f "$XDG_CONFIG_HOME/shell/vars" ] && source "$XDG_CONFIG_HOME/shell/vars"

# Use emacs keybindings even if our EDITOR is set to vi
bindkey -e

# Use modern completion system
autoload -Uz compinit
autoload -Uz colors
compinit
colors

zstyle ':completion:*' auto-description 'specify: %d'
zstyle ':completion:*' completer _expand _complete _correct _approximate
zstyle ':completion:*' format 'Completing %d'
zstyle ':completion:*' group-name ''
zstyle ':completion:*' menu select=2
eval "$(dircolors -b)"
zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*' list-colors ''
zstyle ':completion:*' list-prompt %SAt %p: Hit TAB for more, or the character to insert%s
zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=* l:|=*'
zstyle ':completion:*' menu select=long
zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s
zstyle ':completion:*' use-compctl false
zstyle ':completion:*' verbose true

zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'
zstyle ':completion:*:kill:*' command 'ps -u $USER -o pid,%cpu,tty,cputime,cmd'

# colored GCC warnings and errors
export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# main opts
setopt append_history inc_append_history share_history hist_ignore_all_dups
# on exit, history appends rather than overwrites; history is appended as soon as cmds executed; history shared across sessions; delete older command when duplicate
setopt auto_menu menu_complete # autocmp first menu match
setopt autocd # type a dir to cd
setopt auto_param_slash # when a dir is completed, add a / instead of a trailing space
setopt no_case_glob no_case_match # make cmp case insensitive
setopt globdots # include dotfiles
setopt extended_glob # match ~ # ^
setopt interactive_comments # allow comments in shell
unsetopt prompt_sp # don't autoclean blanklines
stty stop undef # disable accidental ctrl s

# more history opts
HISTFILE="$XDG_CACHE_HOME/zsh_history" # move histfile to cache
HISTCONTROL=ignoreboth # consecutive duplicates & commands starting with space are not saved
HISTSIZE=10000
SAVEHIST=10000

# fzf setup
source <(fzf --zsh) # allow for fzf history widget

# set up prompt
NEWLINE=$'\n'
POWERLINE_START="\ue0d4"
POWERLINE_START_INV="\ue0d2"
POWERLINE_SEPARATOR="\ue0c7"
POWERLINE_STOP="\ue0b4"
POWERLINE_STOP_INV="\ue0b6"
PROMPT_ENTER="" #"\ueb70"
PROMPT_PAD="."
PROMPT_EXTRA_WIDTH=73

precmd() {
  if (($COLUMNS > PROMPT_EXTRA_WIDTH)); then
    local exec_ts=$(($(date +%s%N) - STARTCMD_TS))
    local seconds=$(echo "scale=9; $exec_ts / 1000000000" | bc)
    local hours=$((seconds / 3600))
    local minutes=$(((seconds % 3600) / 60))
    seconds=$((seconds % 60))
    local exec_str=$(printf "%02d:%02d:%06.3f" hours minutes seconds)
    local padding=$(printf %$(($COLUMNS - 73))s | tr ' ' $PROMPT_PAD)
    extra_prompt="%k%f${padding}${POWERLINE_STOP_INV}%K{${FG3}}%F{${BG3}}${POWERLINE_SEPARATOR}%K{${BG3}}%F{${FG3}} took ${exec_str} \uf252%K{${BG3}}%F{${BG2}}${POWERLINE_SEPARATOR}%K{${BG2}}%F{${FG2}}at $(date +%H:%M:%S) \uf017 %k%F{${BG2}}${POWERLINE_START_INV}"
  else
    extra_prompt=""
  fi


  print "" # empty line to increase readability
  print -P "%F{${BG1}}${POWERLINE_START}%K{${BG1}}%F{${FG1}} %y on %M %K{${BG1}}%F{${BG2}}${POWERLINE_SEPARATOR}%K{${BG2}}%F{${FG2}} %n %K{${BG2}}%F{${BG3}}${POWERLINE_SEPARATOR}%K{${BG3}}%F{${FG3}} %~ %K{${BG3}}%F{${FG4}}${POWERLINE_SEPARATOR}%k%F{${FG4}}${POWERLINE_STOP}${extra_prompt}"
  STARTCMD_TS=$(date +%s%N)
}

preexec() {
  STARTCMD_TS=$(date +%s%N)
}
PROMPT="${PROMPT_ENTER} " # nord theme

echo -e "${NEWLINE}\x1b[38;5;137m\x1b[48;5;0m it's $(print -P '%D{%_H:%M%P}\n') \x1b[38;5;180m\x1b[48;5;0m $(uptime -p | cut -c 4-) \x1b[38;5;223m\x1b[48;5;0m $(uname -r) \033[0m" # current

# syntax highlighting
# requires zsh-syntax-highlighting package
#source /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
