package tool

import (
	"errors"
	"math"
	"math/rand"
	"strconv"
	"time"

	"github.com/sony/sonyflake"
)

var (
	flake         *sonyflake.Sonyflake = nil
	paddingLength                      = 13
)

func init() {
	flake = sonyflake.NewSonyflake(sonyflake.Settings{
		StartTime: time.Now(),
		MachineID: func() (uint16, error) {
			return uint16(rand.New(rand.NewSource(time.Now().UnixNano())).Intn(math.MaxUint16)), nil
		},
		CheckMachineID: nil,
	})
}

// GetGID 获取一个全局id
// 原始值最小8位长度,不够长度的填充随机数
func GetGID() (uint64, error) {
	if flake == nil {
		return 0, errors.New(`flake初始化错误`)
	}

	id, err := flake.NextID()
	if err != nil {
		return 0, err
	}

	ids := strconv.FormatUint(id, 10)
	if len(ids) < paddingLength {
		paddingWidth := paddingLength - len(ids)
		v := 1
		for i := 0; i < paddingWidth; i++ {
			v *= 10
		}
		r := uint64(rand.New(rand.NewSource(time.Now().UnixNano())).Intn(v))
		return id*uint64(v) + r, nil
	}

	return id, nil
}
