package tuid

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"strings"
	"time"
)

const (
	layout = "20060102150405"
)

var (
	id      uint32
	oldTime time.Time
)

func New() string {
	now := time.Now()
	if oldTime.After(now) {
		now = oldTime
	}
	if id > 99 {
		id = 0
		now = now.Add(time.Second)
	}
	oldTime = now
	ret := fmt.Sprintf("%s%02d", now.Format(layout), id)
	id = id + 1
	return ret
}

func UID() string {
	b := make([]byte, 5)
	n, _ := rand.Read(b)
	return strings.ToUpper(hex.EncodeToString(b[:n]))
}

func init() {
	id = 0
	oldTime = time.Now()
}
