// Author: NiuJiuRu
// Email: niujiuru@qq.com

package baseapp

import (
	"os"
	"strconv"
	"strings"
)

// 解析命令行参数os.Args参数到map, 以'-'开头的视为key, 后面跟着的为value
var os_args_param map[string]string = make(map[string]string)

func init() {
	procArgsParam(os.Args)
}

func GetArgsParamStr(p string, def string) string {
	s, ok := os_args_param[p]
	if ok {
		return s
	} else {
		return def
	}
}

func GetArgsParamBool(p string, def bool) bool {
	s, ok := os_args_param[p]
	if ok {
		return strings.EqualFold(s, "y") || strings.EqualFold(s, "yes") || strings.EqualFold(s, "true")
	} else {
		return def
	}
}

func GetArgsParamInt64(p string, def int64) int64 {
	s, ok := os_args_param[p]
	if ok {
		i, e := strconv.ParseInt(s, 10, 64)
		if e != nil {
			return def
		}
		return i
	} else {
		return def
	}
}

func GetArgsParamInt(p string, def int) int {
	s, ok := os_args_param[p]
	if ok {
		i, e := strconv.Atoi(s)
		if e != nil {
			return def
		}
		return i
	} else {
		return def
	}
}

func procArgsParam(p []string) {
	if len(p) < 1 {
		return
	}

	var k, v string
	for i := 1; i < len(p); i++ {
		if len(p[i]) < 1 {
			continue
		}

		if p[i][0] == '-' {
			if k != "" {
				os_args_param[k] = v
			}
			k, v = p[i], ""
		} else {
			if k == "" {
				continue
			}
			if v != "" {
				v += " " + p[i]
			} else {
				v = p[i]
			}
		}
	}

	if k != "" {
		os_args_param[k] = v
	}
}

func IsArgsParam(k string) bool {
	_, ok := os_args_param[k]
	return ok
}
