# shellcheck shell=sh
# shellcheck disable=SC2039,3043
___x_cmd_gh_team(){
    param:scope  ___x_cmd_github
    param:subcmd ___x_cmd_gh_team                                       \
        ls              "Interactive UI show team of user"              \
        ll              "list user or org team"                         \
        info            "Get team info by name"                         \
        create          "To create a team"                              \
        "edit|ed"       "To edit a team"                                \
        rm              "To delete a team"                              \
        child           "Lists the child teams of the team specified."  \
        repo            "manage org team repo"
    param:subcmd:try
    param:run

    ___x_cmd_gh_team_ls
}

# Section: List
# shellcheck disable=SC2120
___x_cmd_gh_team_ls(){
    if ___x_cmd_gx_has_format_args "$@"; then
        ___x_cmd_gh_team_ll "$@"
        return
    fi
    param:scope     ___x_cmd_github
    param:dsl       '
options:
    --org           "org space address"                                                 <>:Address=""
    --per_page      "Results per page"                                                  <>:Number=30
    --page          "Page number of the results to fetch."                              <>:Number=1
'
    param:run

    local url="/user/teams"
    if [ -n "$org" ]; then
        url="/orgs/${org##*/}/teams"
    fi

    ___x_cmd_gh_param_init_owner_repo
    local ___gh_error_msg=
    if ___x_cmd_gx_is_interactive_env; then
        local ___X_CMD_TUI_TABLE_FINAL_COMMAND
        local ___X_CMD_TUI_TABLE_CUR_LINE
        local ___X_CMD_TUI_TABLE_CUR_ITEM

        ___x_cmd_gh_tui_app  --url "$url" --per_page "$per_page" --page "$page" \
            --request-code '___x_cmd_gh_get_multi "$url" per_page page' \
            --error-msg "get team list fail" \
            --end ___x_cmd_gh_team_app_status_handler \
            "team.app.awk"
    else
        ___x_cmd_gh_get_multi "$url" per_page page | x jo 2c   .id
    fi
}

___x_cmd_gh_team_app_status_handler(){
    local team_name
    team_name="${___X_CMD_TUI_TABLE_CUR_LINE##*Name: }"
    team_name=${team_name%%
Html_url: *}
    local organization
    organization="${___X_CMD_TUI_TABLE_CUR_LINE##*Organization: }"
    organization=${organization%%
Name: *}
    case "$___X_CMD_TUI_TABLE_FINAL_COMMAND" in
            "ENTER")        printf "%s\n" "$___X_CMD_TUI_TABLE_CUR_LINE"  ;;
            "c")            ___x_cmd_gh_team_create                            ;;
            "u")            ___x_cmd_gh_team_edit              --org "$organization"   "$team_name"                  ;;
            "d")            ___x_cmd_gh_team_rm                --org "$organization"   "$team_name"                  ;;
            "f")            ___x_cmd_gh_team_child             --org "$organization"   "$team_name"                  ;;
            *)              return   ;;
    esac
}
# EndSection

# Section: List
# https://docs.github.com/en/rest/teams/teams#list-teams
___x_cmd_gh_team_ll() {
    param:scope     ___x_cmd_github
    param:dsl       '
options:
    --org           "org space address"                                                 <>:Address=""
    --per_page      "Results per page"                                                  <>:Number=30
    --page          "Page number of the results to fetch."                              <>:Number=1

    --json|-j       "output json data"
    --csv           "output csv data"
    --yml           "output yml data"
'
    param:run

    local _url="/user/teams"
    [ -z "$org" ] || _url="/orgs/${org##*/}/teams"

    if ___x_cmd_gx_output_is_format; then
        ___x_cmd_gh_get_multi "$_url" | ___x_cmd_gx_output_format
    else
        ___x_cmd_gh_get_multi "$_url" | \
            {
                if [ -z "$org" ]; then
                    x jo 2c             .id  .name  .slug  .description  .html_url | \
                    x csv header --add   ID   Name   Slug   Description   Url
                else
                    x jo 2c            .id  .name  .slug  .organization.login  .html_url | \
                    x csv header --add  ID   Name   Slug   Organization       Url
                fi
            } | \
            if [ -n "$csv" ]; then  ___x_cmd_cmds cat
            else                    x csv static_tab
            fi
    fi
}
# EndSection

# Section: Info
# https://docs.github.com/en/rest/teams/teams#get-a-team-by-name
___x_cmd_gh_team_info() {
    param:scope     ___x_cmd_github
    param:dsl      <<A
options:
    #1                  "team name"                 <>
    --org               "org space address"         <>:Address
    --json|-j           "output json data"
A
    param:run
    ___x_cmd_gh_curl get "/orgs/${org##*/}/teams/${1}" | ___x_cmd_team_____ui_handler Info "$1"
}
# EndSection

# Section: Create
# https://docs.github.com/en/rest/teams/teams#create-a-team
# shellcheck disable=2120
___x_cmd_gh_team_create() {
    param:scope     ___x_cmd_github
    param:dsl       <<A
options:
    #1                  "team name"                                                                 <>
    --org               "org space address"                                                         <>:Address
    --description       "A short description of the team"                                           <>:Org_Description=""
    --maintainers       "List organization members username who will become team maintainers"       <>=""
    --repo|-r           "The name of repositories to add the team to"                               <>=""
    --privacy           "The level of privacy this team should have"                                <>="" = secret closed ""
    --parent_team_id    "The ID of a team to set as the parent team"                                <>:Number=""

    --json|-j           "output json data"
A
    param:run

    local name="$1"
    [ -z "$maintainers" ] || maintainers="[${maintainers}]"
    # map append org prefix
    case "${repo}" in
        "") ;;
        *,*)
            local _tmp=
            while true; do
                _tmp="${org}/${repo%%,*},${_tmp}"
                repo="${repo#*,}"
                if [ "${repo#*,}" = "$repo" ]; then
                    repo="[${org}/${repo%%,*},${_tmp}]"
                    break
                fi
            done
            ;;
        *)  repo="[${org}/${repo}]" ;;
    esac

    local gen_gh_json=""
    gen_gh_json="$(param:option2json -json -org -repo +name ${repo:+"repo_names=repo"})"
    gh:debug "$gen_gh_json"
    ___x_cmd_gh_curl post  "/orgs/${org##*/}/teams" "gen_gh_json" | ___x_cmd_team_____ui_handler Creating
}
# EndSection

# Section: Edit
# https://docs.github.com/en/rest/teams/teams#update-a-team
___x_cmd_gh_team_edit() {
    param:scope     ___x_cmd_github
    param:dsl       <<A
options:
    #1                  "old team name"                                 <>
    --org               "org space address"                             <>:Address
    --name              "Changed team name(Empty does not change)"      <>=""
    --description       "The description of the team."                  <>:Org_Description=""
    --privacy           "The level of privacy this team should have"    <>="" = secret closed ""
    --parent_team_id    "The ID of a team to set as the parent team"    <>:Number=""

    --json|-j           "output json data"
A
    param:run

    local gen_gh_json=""
    gen_gh_json="$(param:option2json -org)"
    gh:debug "$gen_gh_json"

    ___x_cmd_gh_curl patch  "/orgs/${org##*/}/teams/${1}" "gen_gh_json" | ___x_cmd_team_____ui_handler Update
}
# EndSection

# Section: Remove
# https://docs.github.com/en/rest/teams/teams#delete-a-team
# shellcheck disable=2154
___x_cmd_gh_team_rm() {
    param:scope     ___x_cmd_github
    param:dsl       <<A
options:
    #1          "The slug of the team name."    <>=""
    --org       "The organization name."        <>:Address

    --yes|-y    "Ignore remove prompt interception"
A
    param:run

    local teamname=""
    for teamname in "$@"; do
        {
            [ "$yes" = "true" ] || ___x_cmd_ui_yesno "Are you sure $org to remove team: $(___x_cmd_ui bold red "$teamname") ?" || continue
            ___x_cmd_gh_curl del "/orgs/${org##*/}/teams/${teamname}" | (
                [ -z "$___X_CMD_GH_IN_TEST" ] || { ___x_cmd_cmds_cat; return; }
                x jo env . gh_resp_msg=.message gh_resp_err=.errors
                if ___x_cmd_gh_http_error; then
                    ___x_cmd_ui_tf  true "[Success]: Remove team $teamname to organizations"
                else
                    ___x_cmd_ui_tf false "Remove team $teamname to organizations failure:" >&2
                    ___x_cmd_gh____handle_resp
                    return 1
                fi
            )

        }
    done
}
# EndSection

# Section: Child
# https://docs.github.com/en/rest/teams/teams#list-child-teams
___x_cmd_gh_team_child() {
    param:scope     ___x_cmd_github
    param:dsl       '
options:
    #1              "The slug of the team name."            <>
    --org           "The organization name."                <>:Address

    --per_page      "Results per page"                      <>:Number=30
    --page          "Page number of the results to fetch."  <>:Number=1
    --json|-j       "output json data"
'
    param:run

    if [ -n "$json" ] || [ -n "$ENFORCE_JSON" ]; then
        ___x_cmd_gh_get_multi "/orgs/${org##*/}/teams/${1}/teams"
    else
        ___x_cmd_gh_get_multi "/orgs/${org##*/}/teams/${1}/teams" | \
            x jo 2c             .id .name .parent.name .description | \
            x csv header --add   ID  Name  Parent       Description | \
            x csv static_tab
    fi
}
# EndSection

# Section: org team UI
___x_cmd_team_____ui_handler(){
    if  [ -n "$ENFORCE_JSON" ] || [ -n "$json" ]; then
        ___x_cmd_cmds_cat
        ___x_cmd_gh_http_error
        return
    fi
    (
        local id=""
        case "$1" in
            Info)
                x jo env . id=.id url=.html_url name=.name gh_resp_msg=.message gh_resp_err=.errors
                _inf_msg="Getting team $2 information successfully"
                _err_msg="Getting team $2 information failure"
                ;;
            Creating|Update)
                x jo env . id=.id url=.html_url name=.name gh_resp_msg=.message gh_resp_err=.errors \
                    slug=.slug owner=.organization.login
                _inf_msg="$1 org team $name successfully"
                _err_msg="$1 org team $name failure"
                ;;
        esac
        if [ -n "$id" ]; then
            ___x_cmd_ui_tf  true "${_inf_msg}:" ${id:+"ID: $id"} ${name:+"Name: $name"} ${slug:+"Slug: $slug"} ${owner:+"Org: $owner"} ${url:+"Url: $url"}
        else
            ___x_cmd_ui_tf false "${_err_msg}:" >&2
            ___x_cmd_gh____handle_resp
            return 1
        fi
    )
}
# EndSection

