package ru.dbotthepony.mc.otm.client.screen.panels.input

import net.minecraft.client.gui.screens.Screen
import ru.dbotthepony.mc.otm.client.minecraft
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import ru.dbotthepony.mc.otm.menu.input.AbstractPlayerInputWithFeedback
import ru.dbotthepony.mc.otm.milliTime

open class NetworkedStringInputPanel<out S : Screen>(
	screen: S,
	parent: EditablePanel<*>?,
	val backend: AbstractPlayerInputWithFeedback<String>,
	x: Float = 0f,
	y: Float = 0f,
	width: Float = 60f,
	height: Float = 11f,
) : TextInputPanel<S>(screen, parent, x, y, width, height) {
	override var isActive: Boolean
		get() = backend.test(minecraft.player)
		set(value) {}

	override fun onFocusChanged() {
		super.onFocusChanged()

		if (isFocusedThis && !backend.test(minecraft.player)) {
			killFocus()
		}
	}

	private var lastChanges = 0L

	override fun onTextChanged(old: String, new: String) {
		lastChanges = milliTime + 1000L
		backend.accept(new)
	}

	override fun tickInner() {
		super.tickInner()

		if (milliTime >= lastChanges) {
			text = backend.value
		}
	}
}
