#!/bin/zsh

# path -> settings -> alias -> functions -> plugins -> prompt

if [ ! -n "${ZSH_VERSION}" ]; then
    echo "Unsupported shell"
    return 1
fi

# get the dir name that current file in
function get_current_dir_name {
     _source="${(%):-%x}"
     _path=$(dirname "$(realpath "$_source")")
     echo $_path
}

# Set basic path to zsh-polyjuice installation
export ZSH_POLYJUICE_PATH=$(get_current_dir_name)
export ZSH_POLYJUICE_PLUGINS_PATH="$ZSH_POLYJUICE_PATH/plugins"
export ZSH_POLYJUICE_ALIAS_PATH="$ZSH_POLYJUICE_PATH/alias"
export ZSH_POLYJUICE_SETTINGS_PATH="$ZSH_POLYJUICE_PATH/settings"
export ZSH_POLYJUICE_FUNCTIONS_PATH="$ZSH_POLYJUICE_PATH/functions"
export ZSH_POLYJUICE_STARSHIP_CONFIG_FILE="$ZSH_POLYJUICE_PATH/../starship/starship_default.toml"
export ZSH_POLYJUICE_HELIX_CONFIG_FILE="$ZSH_POLYJUICE_PATH/../helix/config.toml"

# Load basic settings `zsh/settings`
for _file in "$ZSH_POLYJUICE_SETTINGS_PATH"/*.sh; do
    source "$_file"
done
unset _file

# Load Aliases `zsh/alias`
for _file in "$ZSH_POLYJUICE_ALIAS_PATH"/*.sh; do
    source "$_file"
done
unset _file

# Load self-defined functions
for _file in "$ZSH_POLYJUICE_FUNCTIONS_PATH"/*.sh; do
    source "$_file"
done
unset _file

# Load Plugins
if [[ -f $ZSH_POLYJUICE_PLUGINS_PATH/zsh-autosuggestions/zsh-autosuggestions.zsh ]]; then
    source $ZSH_POLYJUICE_PLUGINS_PATH/zsh-autosuggestions/zsh-autosuggestions.plugin.zsh
    ZSH_AUTOSUGGEST_STRATEGY=(history completion)
    ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE=20
    bindkey '^[l' autosuggest-accept # alt-L to accept autosuggestion
fi
if [[ -f $ZSH_POLYJUICE_PLUGINS_PATH/zsh-autocomplete/zsh-autocomplete.plugin.zsh ]]; then
    source $ZSH_POLYJUICE_PLUGINS_PATH/zsh-autocomplete/zsh-autocomplete.plugin.zsh
fi
if [[ -f $ZSH_POLYJUICE_PLUGINS_PATH/zsh-syntax-highlighting/zsh-syntax-highlighting.plugin.zsh ]]; then
    source $ZSH_POLYJUICE_PLUGINS_PATH/zsh-syntax-highlighting/zsh-syntax-highlighting.plugin.zsh
fi
if [[ -f $ZSH_POLYJUICE_PLUGINS_PATH/fzf-tab/fzf-tab.plugin.zsh ]]; then
    source $ZSH_POLYJUICE_PLUGINS_PATH/fzf-tab/fzf-tab.plugin.zsh # relies on fzf itself and zsh-autocomplete plugin
fi

# using starship as prompt
if (( $+commands[starship] )); then
    export STARSHIP_CONFIG="$ZSH_POLYJUICE_STARSHIP_CONFIG_FILE"
    eval "$(starship init zsh)"
else
    echo '[starship] not found, please install it.'
fi
