# Author:       Li Junhao   l@x-cmd.com     # xrc
# shellcheck    shell=sh    disable=SC2039,SC3043

___x_cmd_http_body() {
    param:subcmd ______x_cmd_http_body               \
        get      "get the value by key in body"         \
        put      "put the kv pair in body"              \
        remove   "remove the kv pair in body by key"    \
        mput     "put multiple kv pair in body"         \
        dump     "dump the body. dump json will dump the body in json form"
    param:subcmd:try
    param:run

    ___x_cmd_http_body _param_help_doc
    return 1
}

______x_cmd_http_body_dump(){
    param:void
    local O="${O:?Provide Object name}"
    case "$1" in
        json)       O=$O ___x_cmd_dict scope body | ___x_cmd_dict_pjson        ;;
        *)          O=$O ___x_cmd_dict scope body ;;
    esac
}

______x_cmd_http_body_get(){
    param:void
    O=$O ___x_cmd_dict get body "${1:?body key}"
}

______x_cmd_http_body_put(){
    param:void
    local body_key="${1:?body key}"
    if [ $# -eq 1 ]; then
        eval O="$O" ___x_cmd_dict put body "\$body_key" "\$${body_key}"
    else
        O=$O ___x_cmd_dict put body "$body_key" "$2"
    fi
}

______x_cmd_http_body_remove(){
    param:void
    O=$O ___x_cmd_dict drop body "${1:?body key}"
}

______x_cmd_http_body_mput(){
    # Notice 1: `___x_cmd_http_qs_put abc=""`  will put the entry { abc: "" }
    # Notice 2: `abc=; ___x_cmd_http_qs_put abc` will NOT put any entry
    param:void
    local value
    local i
    for i in "$@"; do
        # if [[ "$i" = *=* ]]; then
        if [ "$i" != "${i%%=*}" ]; then
            ______x_cmd_http_body_put "${i%=*}" "${i##*=}"
        else
            eval value="\"\$${i}\""
            [ -z "$value" ] || ______x_cmd_http_body_put "$i" "$value"
        fi
    done
}

