# shellcheck shell=sh
# shellcheck disable=SC2039,3043,SC2120

# Section: Help
_____x_cmd_gt_help__token_setting(){
    printf "\n%s %s \n%s\n" \
        "$(___x_cmd_ui yellow 'Run command to add|repleace token:')" \
        "$(___x_cmd_ui bold cyan "\`x gt --cfg token=<token>\`")"   \
        "$(___x_cmd_ui 'https://gitee.com/profile/personal_access_tokens')"
}

_____x_cmd_gt_help__owner_setting(){
    printf "|\n    %s %s\n    %s %s\n" \
        "$(___x_cmd_ui yellow 'Run current command to setup default owner in the current session:')" \
        "$(___x_cmd_ui bold cyan "\`x gt --cur owner=<owner>\`")" \
        "$(___x_cmd_ui yellow 'Run config  command to save default owner to local configure file:')" \
        "$(___x_cmd_ui bold cyan "\`x gt --cfg owner=<owner>\`")"
}

_____x_cmd_gt_help(){
    x help -m gt "$@" 1>&2
    return 1
}
# EndSection

# Section: HTTP header & body & request

___x_cmd_gt_resp_header(){
    if [ -n "$1" ]; then
        ___x_cmd_cmds_awk -v key="$1" '{
            if ($1 ~ key ":$") {
                print $2;
                exit(0)
            }
        }' <"$___X_CMD_GT_TMP/.____x_cmd_gt_curl_header.$$"
    else
        ___x_cmd_cmds_cat "$___X_CMD_GT_TMP/.____x_cmd_gt_curl_header.$$"
    fi
}

___x_cmd_gt_resp_code(){
    ___x_cmd_gt_resp_header | _____x_cmd_gx_get_resp_code_by_header
}

# shellcheck disable=SC2046
___x_cmd_gt_curl(){
    local op="$1"
    local _api_url="$2"
    shift 2
    local ___X_CMD_API_GT_HEADER="-s -H \"Content-Type:application/json;charset=UTF-8\" -D \"$___X_CMD_GT_TMP/.____x_cmd_gt_curl_header.$$\""

    local ___X_CMD_API_GT_TOKEN=""; local _curl_endpoint_tmp="";
    ___x_cmd_gt_cur     ___X_CMD_API_GT_TOKEN:=token  _curl_endpoint_tmp:=endpoint 2>/dev/null
    local ___X_CMD_API_GT_ENDPOINT="${___X_CMD_API_GT_ENDPOINT:-"$_curl_endpoint_tmp"}"

    local ___X_CMD_GT_SHOW_HTTP_CODE=1
    case "$op" in
        get)
            if [ -n "$NO_CACHE" ]; then
                ___x_cmd_api_gt get "$_api_url" $(eval "printf '%s ' $(x curl gencode $(___x_cmd_gt_curl___use_query_data "$@"))")
            else
                x ccmd 10s --        eval "___X_CMD_API_GT_ENDPOINT=$___X_CMD_API_GT_ENDPOINT ___X_CMD_API_GT_TOKEN=$___X_CMD_API_GT_TOKEN ___x_cmd_api_gt get \"$_api_url\" $(eval "printf '%s ' $(x curl gencode $(___x_cmd_gt_curl___use_query_data "$@"))")"
            fi
            ___x_cmd_gt_http_error   eval "___X_CMD_API_GT_ENDPOINT=$___X_CMD_API_GT_ENDPOINT ___X_CMD_API_GT_TOKEN=$___X_CMD_API_GT_TOKEN ___x_cmd_api_gt get \"$_api_url\" $(eval "printf '%s ' $(x curl gencode $(___x_cmd_gt_curl___use_query_data "$@"))")"
            ;;
        post|put|patch|del)
            ___x_cmd_api_gt "$op" "$_api_url" "$(x curl gencode "$@")"
            ___x_cmd_gt_http_error
        ;;
    esac
}

# shellcheck disable=SC2154
___x_cmd_gt_curl___use_query_data(){
    [ $# -gt 0 ] || return
    local name=""
    printf "%s " "-G"
    for name in "$@";
    do
        if [ "$name" = "p" ];then  [ -z "$p" ] || printf "%s " "path==$p";
        else                                      printf "%s " "$name==" ;
        fi
    done
}

___x_cmd_gt_http_error(){
    if [ "$op" = get ] && [ -n "$___X_CMD_CCMD_AGE" ] && [ "$___X_CMD_CCMD_AGE" -ne -1 ]; then
        gt:debug "Is cache data"
        return 0
    fi
    local _http_resp_code=""
    _http_resp_code="$(___x_cmd_gt_resp_code)"
    if [ -n "$_http_resp_code" ] && [ "$_http_resp_code" -ge 200 ] && [ "$_http_resp_code" -le 303 ]; then
        return 0
    else
        [ $# -eq 0 ] || {
            gt:debug "Cache Clear"
            x ccmd invalidate "$@" 1>/dev/null 2>&1
        }
        [ -z "$___X_CMD_GT_SHOW_HTTP_CODE" ] || {
            gt:error "HTTP Code is $_http_resp_code"
            if command -v unset 1>/dev/null; then
                unset ___X_CMD_GT_SHOW_HTTP_CODE
            fi
        }
        return 1
    fi
}

___x_cmd_gt____handle_resp(){
    [ -z "$gt_resp_body" ] || printf "%s" "$gt_resp_body"
    [ -z "$gt_resp_err" ]  || ___x_cmd_gx_printf_error "$gt_resp_err"
}

# EndSection

# Section: Resolve multiple page
___x_cmd_gt_get_multi() {
    # gt:info "Getting data..."
    if [ -n "$page" ] || [ -n "$per_page" ]; then
        ___x_cmd_gt_curl get "$@" page per_page
        return
    fi
    local page=1
    local per_page=100
    local NO_CACHE=1
    if [ -n "$json" ] || [ -n "$ENFORCE_JSON" ]; then
        ___x_cmd_gt_get_multi___json_prt "$@"
    else
        ___x_cmd_gt_get_multi___ui_table "$@"
    fi
    ___x_cmd_gt_http_error
}

___x_cmd_gt_get_multi___ui_table(){
    ___x_cmd_gt_curl get "$@" page per_page
    printf "\n"
    local next_url=""
    _____x_cmd_gt_next_url
    [ -n "$next_url" ] || return

    while [ -n "$next_url" ]; do
        ___x_cmd_gt_curl get "$@" page per_page || return
        printf "\n"
        _____x_cmd_gt_next_url
    done
}

___x_cmd_gt_get_multi___json_prt(){
    local tmp=""
    tmp=$(mktemp)
    ___x_cmd_gt_curl get "$@" page per_page >> "$tmp"
    printf "\n" >> "$tmp"

    local next_url=""
    _____x_cmd_gt_next_url
    if [ -z "$next_url" ] && [ -n "$tmp" ];then
        ___x_cmd_cmds_cat "$tmp"
        x rmrf "$tmp"
        return
    fi

    while [ -n "$next_url" ]; do
        ___x_cmd_gt_curl get "$@" page per_page >> "$tmp"
        printf "\n" >> "$tmp"
        _____x_cmd_gt_next_url
    done
    < "$tmp" x jo q0 \*.\* . | ___x_cmd_gx_merge_multi_page_json_array
    x rmrf "$tmp"
}

_____x_cmd_gt_next_url(){
    next_url="$(___x_cmd_gt_resp_header)"
    next_url="${next_url#*"rel='prev', <"}"
    local tmp_url="${next_url%%">; rel='next'"*}"
    local tmp_page="$page"
    if [ "$next_url" != "$tmp_url" ];then
        page="${next_url#*'&page='}"
        page="${page%%'&'*}"
        # prevent cache latest page data case loop
        [ "$page" != "$tmp_page" ] || {
            next_url=""
            page=""
        }
        # TODO: !!!!! [gitee ERROR] !!!! gt next page response header `link` is error. need resolve byself
        # next_url="${tmp_url#*'.com/api'*}"
        # next_url="$(printf "%s" "$next_url" | sed s/updated_at/updated/g | sed s/created_at/created/g)"
    else
        next_url=""
        page=""
    fi
}

# EndSection

# Section: Default param util

alias ___x_cmd_gt_param_init_owner_repo='
    local owner_repo=""
    ___x_cmd_gt_param_normalize_repo  || return
'

# shellcheck disable=SC2154,SC2034
___x_cmd_gt_param_normalize_repo(){
    local op="$repo"
    [ -n "$op" ] || op="$1"
    case "$op" in
    */*)
        owner_repo="$op"
        ;;
    "")
        local owner=""; local repo="";
        ___x_cmd_gt_cur owner:=owner repo:=repo 2>/dev/null
        case "$repo" in
            */*) owner_repo="$repo"     ;;
            "")  owner_repo="$(___x_cmd_gx_get_owner_repo)" ;;
            *)
                if [ -n "$owner" ]; then
                    owner_repo="${owner}/${repo}"
                else
                    gt:error -h "$(_____x_cmd_gt_help__owner_setting)" "No owner provided. Default owner not set."
                    return 1
                fi
            ;;
        esac
        ;;
    *)
        local x_=""; ___x_cmd_gt_cur get_ owner 2>/dev/null
        if [ -z "$x_" ]; then
            gt:error -h "$(_____x_cmd_gt_help__owner_setting)" "No owner provided. Default owner not set."
            return 1
        fi
        owner_repo="${x_}/${op}"
        ;;
    esac
}

# NOTE: need unset json ENFORCE_JSON. the util func only using on subshell
___x_cmd_gt_owner_type_query(){
    param:void
    local owner="$1";   arg:init gt;
    [ -n "$owner" ]  || M='Please privide owner name' arg:ret:64
    [ "${owner##*/}" = "${owner}" ] || { printf "%s" "repo"; return 0; }
    unset json ENFORCE_JSON
    local types=""
    for types in "org" "user"
    do
        if  ___x_cmd_gt_${types}_info "$owner" 1>/dev/null 2>&1;then
            printf "%s" "$types"
            return
        fi
    done
    return 1
}
# EndSection
