aboutsummaryrefslogtreecommitdiff
path: root/src/texturePacks/java/moe/nea/firmament/features/texturepack/CustomTextReplacements.kt
blob: 71617fd7c5f9defee94aa8de77004371aa35f652 (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
package moe.nea.firmament.features.texturepack

import net.minecraft.server.packs.resources.ResourceManager
import net.minecraft.server.packs.resources.SimplePreparableReloadListener
import net.minecraft.network.chat.Component
import net.minecraft.util.profiling.ProfilerFiller
import moe.nea.firmament.Firmament
import moe.nea.firmament.annotations.Subscribe
import moe.nea.firmament.events.FinalizeResourceManagerEvent
import moe.nea.firmament.util.ErrorUtil.intoCatch

object CustomTextReplacements : SimplePreparableReloadListener<List<TreeishTextReplacer>>() {

	override fun prepare(
        manager: ResourceManager,
        profiler: ProfilerFiller
	): List<TreeishTextReplacer> {
		return manager.listResources("overrides/texts") { it.namespace == "firmskyblock" && it.path.endsWith(".json") }
			.mapNotNull {
				Firmament.tryDecodeJsonFromStream<TreeishTextReplacer>(it.value.open())
					.intoCatch("Failed to load text override from ${it.key}").orNull()
			}
	}

	var textReplacers: List<TreeishTextReplacer> = listOf()

	override fun apply(
        prepared: List<TreeishTextReplacer>,
        manager: ResourceManager,
        profiler: ProfilerFiller
	) {
		this.textReplacers = prepared
	}

	@JvmStatic
	fun replaceTexts(texts: List<Component>): List<Component> {
		return texts.map { replaceText(it) }
	}

	@JvmStatic
	fun replaceText(text: Component): Component {
		// TODO: add a config option for this
		val rawText = text.string
		var text = text
		for (replacer in textReplacers) {
			if (!replacer.match.matches(rawText)) continue
			text = replacer.replaceText(text)
		}
		return text
	}

	@Subscribe
	fun onReloadStart(event: FinalizeResourceManagerEvent) {
		event.resourceManager.registerReloadListener(this)
	}
}