# shellcheck shell=dash disable=1090,2154

___x_cmd_cfgy_obj_set(){
    local X_help_cmd="${X_help_cmd:-x help -m cfgy obj --set}";
    cfgy:arg:config-profile:all
    profile="${profile:-X}"
    cfgy:debug --profile "$profile" --config "$config" --args "$*" set

    [ -z "$config" ] || {
        # You have to reloaded.
        ___x_cmd_cfgy_obj___fset "$profile" "$config" "$@"
        return
    }

    if ___x_cmd_cfgy_obj_isloaded; then
        ___x_cmd_cfgy_obj___set "$profile" "$@"
    else
        ___x_cmd_cfgy_obj___fset "$profile" "$___X_CMD_CFGY_OBJ_DEFAULT_CONFIG" "$@"
    fi
}


___x_cmd_cfgy_obj___set(){
    [ "$#" -gt 1 ] || {
        cfgy:error "Provide profile name, and at least one key value pair"
        return 64
    }

    local profile="$1"; shift

    local x_=; ___x_cmd_cfgy_inner_get_profile_idx_ "$___X_CMD_CFGY_OBJ_PREFIX" "$profile"

    local X_cfgy_varname=
    while [ $# -gt 0 ]; do
        X_cfgy_varname="${1%%=*}"; cfgy:check:varname
        case "$1" in
            *=*)
                eval "${___X_CMD_CFGY_OBJ_PREFIX}_${x_}_${1%%=*}=\"\${1#*=}\""
                shift
                ;;
            *)
                eval "${___X_CMD_CFGY_OBJ_PREFIX}_${x_}_$1=\"\$2\""
                shift 2
        esac
    done
}

___x_cmd_cfgy_obj___fset(){
    [ "$#" -gt 2 ] || {
        cfgy:error "Provide profile name and config-filepath, and at least one key value pair"
        return 64
    }

    local profile="$1"
    local config="$2"
    shift 2

    [ -f "$config" ] || ___x_cmd_cfgy_obj_clear "$config"

    local x_=;  ___x_cmd_cfgy_obj___loadinner_ --local "$config" || return $?
    . "$x_" || return $?

    x_=;    ___x_cmd_cfgy_inner_get_profile_idx_ "$___X_CMD_CFGY_OBJ_PREFIX" "$profile"
    local X_cfgy_varname=
    local op=;  local i; for i in "$@"; do
        X_cfgy_varname="${i%%=*}" cfgy:check:varname
        eval "[ \"\$${___X_CMD_CFGY_OBJ_PREFIX}_${x_}_${i%%=*}\" != \"${i#*=}\" ] || continue"
        op="${op}_1_profile_${x_}_${i}${___X_CMD_UNSEENCHAR_NEWLINE}"
    done

    [ -n "$op" ] || return 0
    op="_1_profile_${x_}_name=${profile}${___X_CMD_UNSEENCHAR_NEWLINE}${op}"

    cfgy:debug --m:op "$op" fset
    ___x_cmd_envy_set "$config" "$op"
}

___x_cmd_cfgy_obj_unset(){
    local X_help_cmd="${X_help_cmd:-x help -m cfgy obj --set}";
    cfgy:arg:config-profile:all
    ___X_CMD_CFGY_OBJ_CURRENT_CONFIG="$config"
    ___X_CMD_CFGY_OBJ_CURRENT_PROFILE="$profile"

    [ "$#" -ge 1 ] || {
        cfgy:error "Provide at least one key value"
        return 64
    }

    local op=""
    local X_cfgy_varname=
    while [ "$#" -gt 0 ]; do
        X_cfgy_varname="$1" cfgy:check:varname
        op="$op $1="
        shift
    done
    eval "___x_cmd_cfgy_obj_set $op"
}

