aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/ledger/utils/telemetry/ContextValue.kt
blob: b5891fcaf0cf6f75302ca6b231f04a052c58394e (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package moe.nea.ledger.utils.telemetry

import com.google.gson.JsonElement
import com.google.gson.JsonObject

interface ContextValue {
	companion object {
		fun <T : Collatable<T>> lazyCollatable(value: () -> Collatable<T>): Collatable<T> {
			return LazyCollatable(value)
		}

		fun lazy(value: () -> ContextValue): ContextValue {
			return object : ContextValue {
				val value by kotlin.lazy(value)
				override fun serialize(): JsonElement {
					return this.value.serialize()
				}
			}
		}

		fun bool(boolean: Boolean): ContextValue {
			return BooleanContext(boolean)
		}

		fun string(message: String): ContextValue {
			return StringContext(message)
		}

		fun jsonObject(vararg pairs: Pair<String, JsonElement>): ContextValue {
			val obj = JsonObject()
			for ((l, r) in pairs) {
				obj.add(l, r)
			}
			return JsonElementContext(obj)
		}

		fun compound(vararg pairs: Pair<String, String>): ContextValue {
			val obj = JsonObject()
			for ((l, r) in pairs) {
				obj.addProperty(l, r)
			}
			// TODO: should this be its own class?
			return JsonElementContext(obj)
		}
	}

	// TODO: allow other serialization formats
	fun serialize(): JsonElement
	interface Collatable<T : Collatable<T>> : ContextValue {
		fun combineWith(overrides: T): T
		fun actualize(): T
	}

	private class LazyCollatable<T : Collatable<T>>(
		provider: () -> Collatable<T>,
	) : Collatable<T> {
		val value by kotlin.lazy(provider)
		override fun actualize(): T {
			return value.actualize()
		}

		override fun combineWith(overrides: T): T {
			return value.combineWith(overrides)
		}

		override fun serialize(): JsonElement {
			return value.serialize()
		}
	}
}