# shellcheck shell=sh disable=SC3043
# Reference: https://www.jianshu.com/p/0deb70e6f395

___x_cmd_mirror_npm(){
    [ "$#" -gt 0 ] || {
        ___x_cmd_mirror_npm___app
        return
    }

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

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

___x_cmd_mirror_npm___app(){
    local _SELECT
    ___x_cmd ui select "_SELECT" \
        "Methods:" \
            "Set npm registry mirror (default is npmmirror)" \
            "List all the npm registry candidates" \
            "Get the current npm registry" \
            "Reset the npm registry to the official"

    case "$_SELECT" in
        1)  ___x_cmd_mirror_npm_set       ;;
        2)  ___x_cmd_mirror_npm_ls        ;;
        3)  ___x_cmd_mirror_npm_current   ;;
        4)  ___x_cmd_mirror_npm_unset     ;;
        *)  mirror:info "Canceled" ; return 1 ;;
    esac
}

___x_cmd_mirror_npm_ls(){
    printf "%s\n" \
        "Code         Url                                               Name"                     \
        "official     https://registry.npmjs.org/                       官方源"                    \
        "npmmirror    https://registry.npmmirror.com/                   npmmirror 镜像/阿里云镜像"  \
        "tencent      http://mirrors.tencent.com/npm/                   腾讯云镜像"                \
        "huawei       https://mirrors.huaweicloud.com/repository/npm/   华为云镜像源"
}

___x_cmd_mirror_npm_current(){
    mirror:info "Current registry [cmd='npm config get registry']"
    ___x_cmd_cmds npm config get registry
}

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

    local url
    url="$(___x_cmd_mirror_npm___url "$1")" || return $?
    mirror:info "Setting npm mirror $url"
    ___x_cmd npm config set registry "$url" || return 1
    mirror:info "Done"
}

___x_cmd_mirror_npm_unset() {
    ___x_cmd_mirror_npm_set   official
}

___x_cmd_mirror_npm___url(){
    ___x_cmd_mirror_npm_ls | \
        ___x_cmd_cmds_awk -v name="$1" 'NR>1 && $1 == name { print $2 ; exit 0;}'
}
