package base

import (
	log "Server-Core/Server/Base/Log"
	"bytes"
	"runtime"
	"strconv"
	"strings"
	"time"
)

// 字符串首字母转大写
func StrFirstToUpper(str string) string {
	if len(str) < 1 {
		return ""
	}
	strArray := []rune(str)
	if strArray[0] >= 97 && strArray[0] <= 122 {
		strArray[0] -= 32
	}
	return string(strArray)
}

// 两个时间戳是否同一天
func IsSameDay(time1, time2 int64, offset int) bool {
	return StartTimestamp(time1, offset) == StartTimestamp(time2, offset)
}

// 获取今天0点时间戳(计算时差)
func TodayStartTimestamp(offset int) int64 {
	return StartTimestamp(time.Now().Unix(), offset)
}

// 获取指定时间戳的0点时间戳(计算时差)
func StartTimestamp(timestamp int64, offset int) int64 {
	timeStr := time.Unix(timestamp, 0).Format("2006-01-02")
	t, _ := time.Parse("2006-01-02", timeStr)
	t2 := t.Unix() + int64(offset)
	if t2 > timestamp {
		t2 -= 86400
	}
	return t2
}

// unicode转中文
func Unicode2Hans(raw []byte) []byte {
	str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(raw)), `\\u`, `\u`, -1))
	if err != nil {
		return raw
	}
	return []byte(str)
}

// 打印Panic堆栈信息
func PanicTrace(kb int) string {
	s := []byte("/src/runtime/panic.go")
	e := []byte("\ngoroutine ")
	line := []byte("\n")
	stack := make([]byte, kb<<10) //4KB
	length := runtime.Stack(stack, true)
	start := bytes.Index(stack, s)
	stack = stack[start:length]
	start = bytes.Index(stack, line) + 1
	stack = stack[start:]
	end := bytes.LastIndex(stack, line)
	if end != -1 {
		stack = stack[:end]
	}
	end = bytes.Index(stack, e)
	if end != -1 {
		stack = stack[:end]
	}
	stack = bytes.TrimRight(stack, "\n")
	return string(stack)
}

// 通用异常捕获
func TryE() {
	errs := recover()
	if errs == nil {
		return
	}

	log.Error("%v\n", errs)
	log.Error(panicTrace(8))
}

func panicTrace(kb int) string {
	s := []byte("/src/runtime/panic.go")
	e := []byte("\ngoroutine ")
	line := []byte("\n")
	stack := make([]byte, kb<<10) //4KB
	length := runtime.Stack(stack, true)
	start := bytes.Index(stack, s)
	stack = stack[start:length]
	start = bytes.Index(stack, line) + 1
	stack = stack[start:]
	end := bytes.LastIndex(stack, line)
	if end != -1 {
		stack = stack[:end]
	}
	end = bytes.Index(stack, e)
	if end != -1 {
		stack = stack[:end]
	}
	stack = bytes.TrimRight(stack, "\n")
	return string(stack)
}
