# shellcheck shell=sh disable=SC3043
# Refer: https://www.jianshu.com/p/dfbb90995a2c

___x_cmd_mirror_pip(){
    [ "$#" -gt 0 ] ||   set -- --help

    local op="$1"; shift
    case "$op" in
        -h|--help)
            ___x_cmd help -m mirror pip         "$@"
            return   ;;
    esac

    ___x_cmd hascmd pip || N=mirror M="[command=pip] not found." log:ret:1
    case "$op" in
        ls|current|set|unset)  ___x_cmd_mirror_pip_"${op}"  "$@" ;;
        *)                     ___x_cmd_mirror___util_subcmd_invalid pip "$@" ;;
    esac
}

___x_cmd_mirror_pip_ls(){
    printf "%s\n" \
        "Code          Url                                                      Name"               \
        "ali           https://mirrors.aliyun.com/pypi/simple                   阿里云镜像"           \
        "wangyi        https://mirrors.163.com/pypi/simple/                     网易镜像"             \
        "huawei        https://mirrors.huaweicloud.com/repository/pypi/simple   华为云镜像"           \
        "tuna          https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple     清华大学镜像"         \
        "ustc          https://mirrors.ustc.edu.cn/pypi/simple                  中国科学技术大学镜像"  \
        "bfsu          https://mirrors.bfsu.edu.cn/pypi/web/simple              北京外国语大学镜像"    \
        "sjtu          https://mirror.sjtu.edu.cn/pypi/web/simple               上海交通大学镜像"      \
        "hust          https://mirrors.hust.edu.cn/pypi/web/simple              华中科技大学镜像"
}

___x_cmd_mirror_pip___url(){
    ___x_cmd_mirror_pip_ls | \
        ___x_cmd_mirror___util_get_url_by_name "$1"
}

___x_cmd_mirror_pip_current(){
    ___x_cmd pip config get global.index-url
}

___x_cmd_mirror_pip_set(){
    [ "$#" -gt 0 ] ||   set -- ali
    case "$1" in
        -h|--help)
            ___x_cmd help -m mirror python set "$@"
            return   ;;
    esac

    # if [ "$1" = "official" ]; then
    #     ___x_cmd_mirror_pip_unset
    #     return
    # fi

    local url
    url="$(___x_cmd_mirror_pip___url "$1")" || return $?
    mirror:info "Setting pip mirror to $url"
    mirror:info "$(___x_cmd pip config set global.index-url "$url")"
}

___x_cmd_mirror_pip_unset(){
    mirror:info "Reset pip mirror to official"
    if res="$(___x_cmd pip config unset global.index-url 2>&1)"; then
        mirror:info "\"$res\""
    else
        mirror:error "\"$res\""
        return 1
    fi
}
