# shellcheck shell=dash

x log init cht

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

    local op="$1"; shift
    case "$op" in
        -s|--search)            ___x_cmd_cht_search "$@" ;;
        -i|:intro)              ___x_cmd_cht_intro ;;
        --ls|-l|:list)          ___x_cmd_cht_ls ;;
        :h|:help)               ___x_cmd_cht_webhelp ;;
        --help|-h)              ___x_cmd_cht_help ;;

        --learn|:learn)         ___x_cmd_cht_learn "$@" ;;
        --1line|:1line|1line)   ___x_cmd_cht_1line "$@" ;;
        --weirdness)            ___x_cmd_cht_weirdness "$@" ;;


        *)                      ___x_cmd_cht___default "$op" "$@"
    esac
}

___x_cmd_cht___default(){
    case "$1" in
        --nocomment|-n)
            local nocomment=1
            shift
            ;;
    esac

    local section="$1";     shift

    [ $# -eq 0 ] || {
        local IFS="+"
        section="$section/$*"
    }

    ___x_cmd_cht___view "$section"
}

___x_cmd_cht_search(){
    local str=
    local keyword=
    while [ $# -gt 0 ]; do
        case "$1" in
            -r) str="${str}r"; shift ;;
            -b) str="${str}b"; shift ;;
            -i) str="${str}i"; shift ;;
            *)  keyword="$1" ; shift  ;;
        esac
    done
    if [ -n "$str" ]; then
        ___x_cmd_cht___view "~${keyword}/${str}"

    else
        ___x_cmd_cht___view "~${keyword}"

    fi
}

___x_cmd_cht_learn(){
    ___x_cmd_cht___view "/$*/:learn"
}

___x_cmd_cht_1line(){
    ___x_cmd_cht___view "/$*/1line"
}

___x_cmd_cht_weirdness(){
    ___x_cmd_cht___view "/$*/weirdness"
}

___x_cmd_cht_intro(){
    ___x_cmd_cht___view ":intro"
}

___x_cmd_cht_ls(){
    x ccmd "$___X_CMD_CHT_CACHE_TIME" -- ___x_cmd_cht___view ":list"
}

___x_cmd_cht_help(){
    x help -m cht
}

___x_cmd_cht_webhelp(){
    ___x_cmd_cht___view ":help"
}

# TODO: After October, consider using bat to view the source code.
___x_cmd_cht___view(){
    if ___x_cmd_hascmd less && [ -t 1 ]; then
        ___x_cmd_cht___curl  "$@" | command less -r # --color=always
    else
        ___x_cmd_cht___curl  "$@"
    fi
}

___X_CMD_CHT_CACHE_TIME=24h

___x_cmd_cht___curl(){
    local nocomment="${nocomment}"
    case "$1" in
        --no-comment)
            nocomment=1
            shift
            ;;
    esac
    # Add cache for 5 day
    cht:debug "url ==> https://cht.sh/$1"

    if [ -z "$nocomment" ]; then
        x ccmd "$___X_CMD_CHT_CACHE_TIME" -- x curl -sS https://cht.sh/"$1"
    else
        x ccmd "$___X_CMD_CHT_CACHE_TIME" -- x curl -sS https://cht.sh/"$1"\?Q
    fi
}
