#!/usr/bin/env bash
# This script will soon be used to resolve $PATHS and LIB_DIR specific to hyde
# wallbash script can source this script to resolve the paths cleanly on a separate shell

if [[ -z "${BASH_SOURCE[0]}" ]]; then
    EXECUTABLE="${0}"
else
    EXECUTABLE="${BASH_SOURCE[0]}"
fi

BIN_DIR=$(dirname "$(which "${EXECUTABLE:-hyde-shell}")")
LIB_DIR=$(realpath "${BIN_DIR}/../lib")
SHARE_DIR=$(realpath "${BIN_DIR}/../share")
PATH="$BIN_DIR:$LIB_DIR/hyde:$PATH" #! I added this to the PATH to make sure that the hyde commands are available in the shell

export BIN_DIR LIB_DIR SHARE_DIR

# shellcheck disable=SC1091
if ! source "${LIB_DIR}/hyde/globalcontrol.sh"; then
    echo "Error: Could not load HyDE, broken installation?"
    exit 1
fi

USAGE() {

    cat <<USAGE
Usage: $(basename "$0") [command]
Commands:
  --help, help, -h : Display this help message
  -i, interactive  : Start an interactive shell
  -r, reload       : Reload HyDE
  zoom             : Zoom in/out Hyprland
  wallbash         : Execute a wallbash script

Available HyDE commands:

$(list_script)

USAGE

}

interactive_shell() {
    history_file="/tmp/.hyde_shell_history"
    touch "$history_file"
    history -r "$history_file"

    while true; do
        read -rep "hyde-shell> " cmd
        if [[ "$cmd" == "exit" ]]; then
            break
        elif declare -f "${cmd%% *}" >/dev/null; then
            eval "$cmd"
            history -s "$cmd"
            history -w "$history_file"
        else
            echo "Available commands:"
            compgen -A function
            echo -e "\e[31mCommand not found: $cmd\e[0m"
            echo -e "\e[32mAvailable commands:\e[0m"
            compgen -A function | while read -r function; do
                echo -e "\e[34m$function\e[0m"
            done
        fi
    done

}

zoom() { #? Zoom in/out Hyprland
    # case
    intensity=${2:-0.1}
    local cursor_state
    local cursor_state
    cursor_state="$(hyprctl getoption cursor:no_hardware_cursors 1 -j | jq .int)"
    trap 'hyprctl -q keyword cursor:no_hardware_cursors "$cursor_state"' EXIT
    case $1 in
    in) #? Zoom in
        hyprctl -q keyword cursor:no_hardware_cursors 1
        hyprctl -q keyword cursor:zoom_factor "$(hyprctl getoption cursor:zoom_factor -j | jq --arg zoomFactor "$intensity" '.float + ($zoomFactor | tonumber)')"
        ;;
    out) #? Zoom out
        hyprctl -q keyword cursor:no_hardware_cursors 1
        hyprctl -q keyword cursor:zoom_factor "$(
            hyprctl getoption cursor:zoom_factor -j | jq --arg zoomFactor "$intensity" '
    if (.float - ($zoomFactor | tonumber)) < 1 then 1 else (.float - ($zoomFactor | tonumber)) end'
        )"
        ;;
    reset) #? Reset Zoom
        hyprctl -q keyword cursor:zoom_factor 1
        ;;
    *)
        echo "Usage: zoom [in|out|reset] [intensity]"

        ;;
    esac
}

call_wallbashScript() {
    local scriptName=$1
    shift
    local args=("${@}")
    local dirs=("${wallbashDirs[@]}")
    sanitized_dirs=()
    for dir in "${dirs[@]}"; do
        if [[ -d "$dir" ]]; then
            sanitized_dirs+=("$dir")
        fi
    done
    dirs=("${sanitized_dirs[@]}")
    script_path=$(find "${dirs[@]}" -type f -path "*/scripts/*" -name "${scriptName}.sh" -exec echo {} \; -quit)

    for func in $(compgen -A function); do
        export -f "${func?}"
    done

    if [[ -n "$script_path" ]]; then
        "$script_path" "${args[@]}"
    else
        case $scriptName in
        *)
            echo "Usage: wallbash [script-name] [args]"
            echo "Executes the specified wallbash script with the provided arguments."
            echo "Available scripts:"
            for dir in "${dirs[@]}"; do
                if [[ -d "$dir" ]]; then
                    echo -e "\n[ $dir ]"
                    find "$dir" -type f -path "*/scripts/*" -name "*.sh" -exec basename {} \;
                fi
            done
            ;;
        esac
    fi

}

hyde_reload() {

    print_log -sec "hyde" "Reloading HyDE"
    "$LIB_DIR/hyde/swwwallcache.sh" -t ""
    "$LIB_DIR/hyde/theme.switch.sh"
}

list_script() {
    find "$LIB_DIR/hyde" -type f \( -name "*.sh" -o -name "*.py" \) -exec basename {} \;
}

if [[ ! "${BASH_SOURCE[0]}" != "${0}" ]]; then

    case $1 in
    -i | interactive)
        interactive_shell
        ;;
    -r | reload)
        hyde_reload
        ;;
    zoom)
        shift
        zoom "$@"
        ;;
    wallbash)
        shift
        call_wallbashScript "$@"
        ;;
    --help | help | -h)
        USAGE
        ;;
    --list-script)
        list_script
        ;;
    --list-script-path)
        find "$LIB_DIR/hyde" -type f \( -name "*.sh" -o -name "*.py" \) -exec echo {} \;
        ;;
    "")
        for func in $(compgen -A function); do
            export -f "${func?}"
        done
        ;;
    *)
        if [ -f "${LIB_DIR}/hyde/${1}.sh" ]; then
            bash "${LIB_DIR}/hyde/${1}.sh" "${@:2}"
        elif [ -f "${LIB_DIR}/hyde/${1}.py" ]; then
            python "${LIB_DIR}/hyde/${1}.py" "${@:2}"
        elif [ -f "${LIB_DIR}/hyde/${1}" ]; then
            "${LIB_DIR}/hyde/${1}" "${@:2}"
        elif [ -f "${1}" ] && [ -x "${1}" ]; then
            "$1" "${@:2}"
        else
            echo "Command not found: $1"
            echo "Available commands:"
            list_script
        fi
        ;;
    esac

fi
