# shellcheck shell=dash disable=2034,3028

# exectime

___x_cmd_theme_exectime(){
    local data="$1"
    case "$data" in
        on|off) ___x_cmd_theme_exectime_"$1" ;;
    esac
    ___X_CMD_THEME_FEATURE_exectime="$data"
}

___x_cmd_theme_exectime_on(){
    [ -z "$___X_CMD_THEME_EXECTIME___ENABLE" ] || return "$___X_CMD_THEME_EXECTIME___ENABLE"
    x_replhook_feature="theme feature exectime" ___x_cmd replhook_enable || return
    ___x_cmd_replhook_preexec_add ___x_cmd_theme_exectime___preexec
    ___x_cmd_replhook_precmd_add  ___x_cmd_theme_exectime___precmd
    ___X_CMD_THEME_EXECTIME___ENABLE=0
}

___x_cmd_theme_exectime_off(){
    [ -n "$___X_CMD_THEME_EXECTIME___ENABLE" ] || return
    ___x_cmd_replhook_preexec_rm ___x_cmd_theme_exectime___preexec
    ___x_cmd_replhook_precmd_rm  ___x_cmd_theme_exectime___precmd

    unset ___X_CMD_THEME_EXECTIME___START
    unset ___X_CMD_THEME_EXECTIME___END
    unset ___X_CMD_THEME_EXECTIME___ENABLE
    unset x_exectime_current
    unset x_exectime_start
    unset x_exectime_end
}

___x_cmd_theme_exectime___preexec(){
    ___x_cmd_theme_exectime___record
}

___x_cmd_theme_exectime___precmd(){
    ___x_cmd_theme_exectime___record

    if [ -z "$___X_CMD_THEME_EXECTIME___END" ]; then
        unset ___X_CMD_THEME_EXECTIME___START
        unset x_exectime_end
    elif [ -n "$___X_CMD_THEME_EXECTIME___START" ]; then
        x_exectime_start="$___X_CMD_THEME_EXECTIME___START"
        x_exectime_end="$___X_CMD_THEME_EXECTIME___END"
        unset ___X_CMD_THEME_EXECTIME___START
        unset ___X_CMD_THEME_EXECTIME___END
    fi
}

___x_cmd_theme_exectime___record(){
    # $EPOCHREALTIME from zsh module zsh/datetime
    x_exectime_current="${EPOCHREALTIME:-"$(date +%s)"}"
    if [ -n "$___X_CMD_THEME_EXECTIME___START" ]; then
        ___X_CMD_THEME_EXECTIME___END="$x_exectime_current"
    else
        ___X_CMD_THEME_EXECTIME___START="$x_exectime_current"
    fi
}
