aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/ledger/UUIDUtil.kt
blob: ddfb8c27b80be5a60024f6fd59e1bb306efe9459 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package moe.nea.ledger

import com.mojang.util.UUIDTypeAdapter
import io.azam.ulidj.ULID
import net.minecraft.client.Minecraft
import java.time.Instant
import java.util.UUID
import kotlin.random.Random

object UUIDUtil {
	@JvmInline
	value class ULIDWrapper(
		val wrapped: String
	) {
		init {
			require(ULID.isValid(wrapped))
		}
	}

	fun parseDashlessUuid(string: String) = UUIDTypeAdapter.fromString(string)
	val NIL_UUID = UUID(0L, 0L)
	fun getPlayerUUID(): UUID {
		val currentUUID = Minecraft.getMinecraft().thePlayer?.uniqueID
			?: Minecraft.getMinecraft().session?.playerID?.let(::parseDashlessUuid)
			?: lastKnownUUID
		lastKnownUUID = currentUUID
		return currentUUID
	}

	fun createULIDAt(timestamp: Instant): ULIDWrapper {
		return ULIDWrapper(ULID.generate(
			timestamp.toEpochMilli(),
			Random.nextBytes(10)
		))
	}

	private var lastKnownUUID: UUID = NIL_UUID

}