# shellcheck shell=sh disable=SC3043
# Reference: https://zhuanlan.zhihu.com/p/35856841

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

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

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

___x_cmd_mirror_yarn_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_yarn___url(){
    ___x_cmd_mirror_yarn_ls | \
        ___x_cmd_mirror___util_get_url_by_name "$1"
}

___x_cmd_mirror_yarn_current(){
    yarn config get registry
}

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

    local url
    url="$(___x_cmd_mirror_yarn___url "$1")" || return $?
    mirror:info "yarn mirror $url"
    yarn config set registry "$url" >/dev/null || {
        mirror:error "Failed to set yarn mirror"
        return 1
    }
}

___x_cmd_mirror_yarn_unset() {
    ___x_cmd_mirror_yarn_set   official
}
