#!/bin/zsh

# This script is modeled after Omarchy's omarchy-theme-set script and my theme-switching
# approach is modeled after Omarchy's theme-switching approach.
# (See: https://github.com/basecamp/omarchy)
# Omarchy is licensed under the MIT License. See the original LICENSE file for details at:
# https://github.com/basecamp/omarchy/blob/master/LICENSE
# Copyright (c) David Heinemeier Hansson

##########################################################################################

theme_update_terminal() {
    case "$TERMINAL" in
        ("havoc" | "foot")
            echo "TODO: theme update for havoc or foot not yet implemented"
            ;;
        ("kitty")
            killall -SIGUSR1 kitty
            ;;
    esac
}

theme_update_tmux() {
    tmux source-file $DIR_THEME_SETTINGS/.current-theme/tmux.conf
}

theme_update_neovim() {
    nvim_stdpath_run=$(dirname $(
        nvim -l <(echo "vim.cmd.echo('stdpath(\"run\")')") > /dev/stdout 2>&1
    ))
    find "$nvim_stdpath_run" -type s -name "nvim*" 2> /dev/null |
        while IFS= read -r nvim_server; do
            timeout 2s nvim --server "$nvim_server" \
                --remote-expr "execute('lua ThemeUpdate()')" \
                > /dev/null 2>&1
        done
}

[[ ! -z $1 ]] && raw_target="$1" ||
    raw_target=$(
        find $DIR_THEME_SETTINGS -mindepth 1 -maxdepth 1 -type d -exec basename -- {} \; |
            fzf
    )

target_theme="$DIR_THEME_SETTINGS/$(echo $raw_target | tr ' ' '-' | tr '[:upper:]' '[:lower:]')"
[[ ! -d "$target_theme" ]] && echo "theme not found: $target_theme" && exit 1

ln -snf "$target_theme" $DIR_THEME_SETTINGS/.current-theme

theme_update_terminal
theme_update_tmux
theme_update_neovim &
# theme_update_mutt # TODO: possible? or does it just use terminal colors anyway?
# theme_update_reaper # TODO: implement

theme-update-wallpaper "zz-default-for-theme" &
