# shellcheck    shell=dash

## How to use it?
# This is a framework

# Generate code: x awk codegen --amod arr,buf,fs,log,obj --xfile tui/lib/abc.awk,tui/lib/cde.awk,tui/lib/cde.awk
# Generate code: x awk codegen --envar abc,cde,efg
# x awk invokecodegen --amod arr,buf,fs,log,obj --xfile tui/lib/abc.awk,tui/lib/cde.awk,tui/lib/cde.awk

xrc:mod:lib     awk     init util

___x_cmd_awk___main(){
    local op="$1";
    case "$op" in
        stresstest|impl|impl_|file|arg|code|src|try|end|version_|version)
            shift; "___x_cmd_awk_${op}" "$@" ;;
        get_utf8_)
            shift; ___x_cmd_awk___get_utf8_ "$@" ;;
        *)
            ___x_cmd_cmds_awk "$@" ;;
    esac
}

___x_cmd_awk_file(){
    # This is core ...
    local fp="$1"; [ "$#" -eq 0 ] || shift 1
    local code
    if ! code="$(eval ___x_cmd_cmds_cat "$(___x_cmd_awk_lib)" "$fp")"; then
        printf "%s\n" "Cannot find out code."
        return 1
    fi
    ___x_cmd_cmds_awk "$@" "$code"
}

___x_cmd_awk_arg(){
    printf "%s %s" "-f" "awk/lib/core.awk"
    for i in "$@"; do
        printf " -f %s " "awk/lib/${i}.awk"
        # case "$i" in
        #     arr|bit|char|default|jiprint|jiter|jparse|json|math|ord|re|str|ui|var|wcwdith)
        # esac
    done
}

___x_cmd_awk_code(){
    # This will be in file
    local code="$1"; [ "$#" -eq 0 ] || shift 1
    ___x_cmd_cmds_awk "$@" "$(eval ___x_cmd_cmds_cat "$(___x_cmd_awk_lib)")
${code}"
}

___x_cmd_awk_src(){
    local IFS=" "
    eval ___x_cmd_cmds_cat "$(___x_cmd_awk_lib) $*"
}

___x_cmd_awk_try(){
    local code="$1"; [ "$#" -eq 0 ] || shift 1
    local USE="$___X_CMD_AWK_ALL_LIB"
    ___x_cmd_cmds_awk "$@" "$(eval ___x_cmd_cmds_cat "$(___x_cmd_awk_lib)")
$code"
}

___x_cmd_awk_end(){
    local code="$1"; [ "$#" -eq 0 ] || shift 1
    if [ "$code" = - ]; then
        code="$(___x_cmd_cmds_cat)"
    fi
    local USE="$___X_CMD_AWK_ALL_LIB"
    printf "" | ___x_cmd_cmds_awk "$@" "$(eval ___x_cmd_cmds_cat "$(___x_cmd_awk_lib)")
END{
    $code
}"
}

# Section: lib
___x_cmd_awk_lib(){
    local IFS="$___X_CMD_UNSEENCHAR_NEWLINE"

    printf "%s\n" "default,$USE" | tr "," "\n" | while read -r lib; do
        [ -z "$lib" ] && continue
        xrc which "awk/lib/${lib}.awk"
        printf " "
        # printf "%s\n" "./${lib}.awk"
    done | tr "\n" " "
}

___X_CMD_AWK_ALL_LIB="bit,math,ord,char,str,wcwidth,arr,ui,json,jiparse,jiparse_flat"
# EndSection

# Section: stresstest
___x_cmd_awk_stresstest(){
    local start; start="$(date +%s)"
    time awk -v LOOP="${1:-10000000}" '
    BEGIN{
        for (j=1; j<=100; j++) a = a " " j
        print "start"
    }
    END{
        for (i=1; i<=LOOP; ++i) {
            length(str)
        }
    }' <<A

A

    local end; end="$(date +%s)"
    printf "Time Elapsed(seconds): %s\n" "$((end - start))"
}
# EndSection
