package game

import (
	"fmt"
	"runtime"
	"strconv"
	"strings"
	"sync"

	"github.com/gofrs/uuid"
)

//获取线程ID
func GoID() int {
	var buf [64]byte
	n := runtime.Stack(buf[:], false)
	idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
	id, err := strconv.Atoi(idField)
	if err != nil {
		panic(fmt.Sprintf("cannot get goroutine id: %v", err))
	}
	return id
}

var uuidIntMap = make(map[string]int)
var uuidIntMapLock sync.Mutex

//获取int型的自增id（范围1~2111111111）
func GetUuidInt(key string) int {
	uuidIntMapLock.Lock()
	defer uuidIntMapLock.Unlock()
	id := uuidIntMap[key] + 1
	if id > 2111111111 {
		id = 1
	}
	uuidIntMap[key] = id
	return id
}

func NewUUID() string {
	uidStr := ""
	uid, err := uuid.NewV1()
	if err == nil {
		uidStr = strings.ReplaceAll(uid.String(), "-", "")
	}
	return uidStr
}
