# shellcheck shell=dash

xrc:mod:lib  hub   org/member

___x_cmd_hub_org(){
    local X_help_cmd='___x_cmd_hub___help org'
    help:arg-null:parse

    [ $# -gt 0 ]    ||  set -- --help
    local op="$1";  shift
    case "$op" in
        -h|--help)      ___x_cmd help -m hub org    "$@" ;;

        # TODO: remove _ls_name ...
        ls|_ls_name|create|rm|member)
                        ___x_cmd_hub_org_"$op"      "$@" ;;
        *)
                        ___x_cmd_hub_u_subcmd_invalid file "$op" "$@" ;;
    esac
}

___x_cmd_hub_org_create(){
    local X_help_cmd='___x_cmd_hub___help org create'
    help:arg-null:parse

    local orgname="$1"
    hub:info "Organization names on x-cmd hub will default to having the prefix 'o-' added. "

    resp="$(___x_cmd_hub_u_curl post /api/v0/org -- "name=${orgname}")" || {
        ___x_cmd_hub_u_handle_resp false "Failed to create org $1"
        return 1
    }

    printf "%s" "$resp" | {
        local name=
        ___x_cmd jo env . .name
        ___x_cmd_hub_u_handle_resp true "Org $name created"
    }
}

___x_cmd_hub_org_ls(){
    local X_help_cmd='___x_cmd_hub___help org ls'
    help:arg:parse

    local resp=; resp="$(___x_cmd_hub_u_curl get /api/v0/org)" || {
        ___x_cmd_hub_u_handle_resp false "Failed to list orgs"
        return 1
    }

    printf "%s" "$resp" | ___x_cmd jo
}

___x_cmd_hub_org__ls_name(){
    local X_help_cmd='___x_cmd_hub___help org _ls_name'
    help:arg:parse

    local resp=; resp="$(___x_cmd_hub_u_curl get /api/v0/org)" || {
        ___x_cmd_hub_u_handle_resp false "Failed to list orgs"
        return 1
    }

    printf "%s" "$resp" | ( ___x_cmd jo env .\* .name -- 'printf "%s\n" "$name"' )
}

___x_cmd_hub_org_rm(){
    local X_help_cmd='___x_cmd_hub___help org rm'
    help:arg-null:parse

    local name="$1"

    local resp=; resp="$(___x_cmd_hub_u_curl delete "/api/v0/org/$name")" || {
        ___x_cmd_hub_u_handle_resp false "Failed to delete org $1"
        return 1
    }

    ___x_cmd_hub_u_handle_resp true "Org $name deleted"
}
