aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/ledger/utils/telemetry/Context.kt
blob: 3c30a52ae4caa641dc6d42f77c17fbf5ca367825 (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
package moe.nea.ledger.utils.telemetry

import com.google.gson.JsonObject

class Context(val data: MutableMap<String, ContextValue> = mutableMapOf()) : ContextValue.Collatable<Context> {

	inline fun <reified T : ContextValue> getT(key: String): T? {
		return get(key) as? T
	}

	fun get(key: String): ContextValue? {
		return data[key]
	}

	fun add(key: String, value: ContextValue) {
		data[key] = value
	}

	@Suppress("NOTHING_TO_INLINE")
	private inline fun <T : ContextValue.Collatable<T>> cope(
		left: ContextValue.Collatable<T>,
		right: ContextValue
	): ContextValue {
		return try {
			left.combineWith(right as T)
		} catch (ex: Exception) {
			// TODO: cope with this better
			right
		}
	}

	override fun combineWith(overrides: Context): Context {
		val copy = data.toMutableMap()
		for ((key, overrideValue) in overrides.data) {
			copy.merge(key, overrideValue) { old, new ->
				if (old is ContextValue.Collatable<*>) {
					cope(old, new)
				} else {
					new
				}
			}
		}
		return Context(copy)
	}

	override fun actualize(): Context {
		return this
	}

	override fun serialize(): JsonObject {
		val obj = JsonObject()
		data.forEach { (k, v) ->
			obj.add(k, v.serialize())
		}
		return obj
	}
}