# shellcheck shell=dash
# NOTE: For gits app share code

# Section: Get Owner Repo
___x_cmd_gx_get_owner_repo() {
    command git config --get remote.origin.url 2>/dev/null | ___x_cmd_gx____get_owner_repo "$1"
}

___x_cmd_gx____get_owner_repo(){
    local _HOST=""; _HOST="$(command cat)"
    local _HOST_ADDR="$1"
    [ -z "$_HOST_ADDR" ] || _HOST="${_HOST##*"$_HOST_ADDR"}"

    printf "%s\n" "" | command awk -v HOST="$_HOST" -v HOST_ADDR="$_HOST_ADDR" '
    BEGIN{
        git_ssh_url = "git@.*"
        git_http = "http.*"
        if(HOST_ADDR == "") addr = 1
    }
    addr == 0{
        _idx = index(HOST, "/")
        words = substr(HOST, _idx + 1)
        if(match(words,".*git$"))  printf ("%s", substr(words,RSTART,RLENGTH-4))
        else                       printf ("%s", words)
    }
    (HOST ~ git_ssh_url) && (addr == 1){
        if(HOST ~ ".*:.*git$"){
            if(match(HOST,":.*git$")) _word = substr(HOST,RSTART+1,RLENGTH-5)
            else                      _word = substr(HOST,1)
        }else{
            l = split(HOST, arr, ":")
            word = arr[2]
            if(match(word,"^.*.git$"))      _word = substr(word,RSTART,RLENGTH-4)
            else                            _word = substr(word,1)
        }
        check(_word)
    }
    (HOST ~ git_http) && (addr == 1){
        words = HOST
        for(i=0; i<3; ++i){
            _idx = index(words, "/")
            words = substr(words, _idx + 1)
        }
        if (match(words,"^.*(\\.git)$")) _word =  substr(words, RSTART,RLENGTH-4)
        else _word = words
        check(_word)
    }

    function check(s,   _idx){
        if((s ~ "(^(git:)?[0-9]+/.*)")|| (s ~ "^\\/")){
            _idx = index(s, "/")
            ownerepo = substr(s, _idx + 1)
        }else  printf ("%s", s)
    }
    '
}
# EndSection

# Section: Get http code
_____x_cmd_gx_get_resp_code_by_header(){
    command awk '($1 ~ "HTTP/(1.*|2)$" && $3 != "Connection" && $4 != "established") {
        print  int($2);
        exit(0)
    }'
}
# EndSection

# Section: Avatar Sdict To CSV
# shellcheck disable=SC2016
___x_cmd_gx_avatar_sdict_to_csv(){
    x csv awk 'BEGIN{ printf("%s,%s\n", "Key","Value") }
        {
            l = split($0,arr, "=")
            if (l > 2){
                for (i=1 ; i<=l-2; ++i){
                    _name = _name  arr[i] "="
                }
                _name = _name  arr[ l-1 ]
                print "\""_name"\"" "," arr[l]
                _name=""
            } else if (l == 2){
                dex = index($0, "=")
                name = substr($0, 1, dex-1 )
                id = substr($0, dex+1 )
                print "\""name"\"" "," id
            }
        }'
}
# EndSection

# Section: Export CSV
___x_cmd_gx_tocsv(){
x ja '
BEGIN{
    IS_LIST=0
    IS_DICT=0
    data = ""
    pre_key=""
}

function handle_dict(keypath,key,           key_l, _key, j, _data){
    # keypath = keypath SUBSEP key
    # _data = data "."key
    key_l = O[keypath L ]
    pre_key = pre_key "."key
    for(j=1; j<=key_l; ++j){
        _key = juq(O[ keypath SUBSEP  "\""j"\"" ])
        if (O[ keypath SUBSEP  "\""_key"\"" ] == "{"){
            handle_dict(keypath SUBSEP "\""_key"\"", _key )
            pre_key = pre_key "."key
        }
        else {
            _data = pre_key"."_key " "
            data = data _data
        }
        if( key_l == j)pre_key = ""
    }
}

function list(              key, i, len, keypath){
    len = O[kp("1", "1") L]
    for(i=1; i<=len; ++i){
        key = juq(O[kp("1", "1", i) ])
        keypath = SUBSEP "\"1\"" SUBSEP "\"1\"" SUBSEP "\""key"\""
        if (O[ keypath ] == "{") handle_dict(keypath, key)
        else if ((key != "")&&(key != "{"))data = data "."key " "
    }
}
function dict(        key, i, len, keypath){
    len = O[kp("1") L]
    for(i=1; i<=len; ++i){
        key = juq(O[kp("1", i) ])
        keypath = SUBSEP "\"1\""  SUBSEP "\""key"\""
        if (O[ keypath ] == "{") handle_dict(keypath, key)
        else if((key != "")&&(key != "{"))data = data "."key " "
    }
}

END{
    if( O[kp("1")] == "[") IS_LIST = 1
    else IS_DICT = 1

    if (IS_LIST == 1) data = data "| x jo 2c "  ;   list()
    if (IS_DICT == 1) data = data "| x ja jl2c ";   dict()

    print data
}
'
}
# EndSection

# Section: Merge Multi Page JSON Array
___x_cmd_gx_merge_multi_page_json_array(){
    command awk 'BEGIN{ print "["}
        END{ print "]"}
        {
            if ($0 == "") next
            if ((NR != 1) && ( aaa == 0 )) print ","
            if (($0 == "{") || ( $0 == "[")) aaa++
            if (($0 == "}") || ( $0 == "]")) aaa--
            print $0
        }'
}
# EndSection

# Section: Interactive judge
___x_cmd_gx_is_not_interactive_env() {
    ! ___x_cmd_is_stdout2tty || ! ___x_cmd_runmode_allow_manual
}

___x_cmd_gx_is_interactive_env(){
    ! ___x_cmd_gx_is_not_interactive_env
}
# EndSection

# Section: Is No Color && Print Error Message
___x_cmd_gx_stdout_is_no_color(){
    ! ___x_cmd_is_stdout2tty || ! ___x_cmd_runmode_allow_manual || [ -n "$NO_COLOR" ]
}

___x_cmd_gx_stderr_is_no_color(){
    [ ! -t 2 ]               || ! ___x_cmd_runmode_allow_manual || [ -n "$NO_COLOR" ]
}

___x_cmd_gx_printf_error(){
    if ___x_cmd_gx_stderr_is_no_color; then
        printf "  - ErrorMsg: '%s'\n" "$1" >&2
    else
        printf "  \033[31m-\033[0m \033[1mErrorMsg: \033[90m'\033[31m%s\033[90m'\033[0m\n" "$1" >&2
    fi
}

___x_cmd_gx_output_is_format(){
    [ -n "$json" ] || [ -n "$yml" ] || [ -n "$ENFORCE_JSON" ] || return 1

    return 0
}

___x_cmd_gx_has_format_args(){
    local i=""; for i in "$@"; do
        case "$i" in
            --json|-j|--yml|--csv)    return 0 ;;
        esac
    done
    return 1
}

___x_cmd_gx_output_format(){
    if [ -n "$json" ] || [ -n "$ENFORCE_JSON" ]; then
        ___x_cmd_cmds cat
    elif [ -n "$yml" ]; then
        x yml j2y
    fi
}

# EndSection
