# shellcheck shell=dash disable=1090

# ENV ___X_CMD_CFGY_NAME
# ENV ___X_CMD_CFGY_OBJ_PREFIX
# ENV ___X_CMD_CFGY_OBJ_DEFAULT_CONFIG

# @shgen fromx_ --helpcmd 'x help -m cfgy obj get' ___x_cmd_cfgy_obj_get
# x shgen fromx_ --helpcmd 'x help -m cfgy obj get' ___x_cmd_cfgy_obj_get

___x_cmd_cfgy_obj_get(){
    local x_="";
    local X_help_cmd="${X_help_cmd:-x help -m cfgy obj --get}";
    ___x_cmd_cfgy_obj_get_ "$@" || return $?
    printf "%s\n" "$x_"
}

___x_cmd_cfgy_obj_get_(){
    cfgy:arg:config-profile:local
    local default
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --default)
                [ "$#" -gt 1 ] || M="Provide default value" N=cfgy log:ret:64
                default="$2"
                shift 2; continue
            ;;
        esac
        cfgy:arg:config-profile:parse
    done

    local X_help_cmd="${X_help_cmd:-x help -m cfgy obj --get_}";
    [ -z "$X_arg_help" ] || {
        ___x_cmd help --show
        return 1
    }

    [ $# -eq 1 ] || {
        cfgy:error "Invalid argument, missing an argument"
        return 64
    }

    cfgy:debug --profile "$profile" --config "$config" --args "$*" get
    local key="$1"
    local X_cfgy_varname="$key"; cfgy:check:varname

    [ -z "$config" ] || {
        ___x_cmd_cfgy_obj_fget_ \
            "$config"           \
            "$profile"          \
            "$key" "$default"
        return
    }

    if ___x_cmd_cfgy_obj_isloaded; then
        ___x_cmd_cfgy_inner_get_ \
            "$profile" \
            "$___X_CMD_CFGY_OBJ_PREFIX" \
            "$key" "$default"
    else
        ___x_cmd_cfgy_obj_fget_ \
            "$___X_CMD_CFGY_OBJ_DEFAULT_CONFIG" \
            "$profile" \
            "$key" "$default"
    fi
}

___x_cmd_cfgy_obj_fget_(){
    local config="${1}"
    local profile="$2"
    local key="$3"
    local default="$4"

    x_=;    ___x_cmd_cfgy_obj___loadinner_ --local "$config" || return $?
    . "$x_" || return $?
    x_=;    ___x_cmd_cfgy_inner_get_ "$profile" "$___X_CMD_CFGY_OBJ_PREFIX" "$key" "$default"
}
