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

import com.mojang.blaze3d.platform.InputConstants
import net.minecraft.client.gui.components.EditBox
import net.minecraft.client.gui.screens.Screen
import net.minecraft.network.chat.Component
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import ru.dbotthepony.mc.otm.client.screen.panels.Widget2Panel
import ru.dbotthepony.mc.otm.core.TextComponent

open class EditBoxPanel<out S : Screen>(
	screen: S,
	parent: EditablePanel<*>?,
	x: Float = 0f,
	y: Float = 0f,
	width: Float = 0f,
	height: Float = 20f,
	val defaultText: Component = TextComponent("")
) : Widget2Panel<S, EditBox>(screen, parent, x, y, width, height) {
	override fun makeNew(): EditBox {
		return object : EditBox(font, 0, 0, width.toInt(), height.toInt().coerceAtMost(20), defaultText) {
			override fun isHoveredOrFocused(): Boolean {
				return this@EditBoxPanel.isHovered
			}

			override fun isFocused(): Boolean {
				return this@EditBoxPanel.isFocusedThis
			}
		}
	}

	override fun copyValues(new_widget: EditBox, old_widget: EditBox) {
		new_widget.value = old_widget.value
	}

	override fun tickInner() {
		super.tickInner()
		widget?.tick()
	}

	override fun configureNew(widget: EditBox, recreation: Boolean) {
		widget.isFocused = isFocusedThis
	}

	override fun onFocusChanged() {
		widget?.isFocused = isFocusedThis
	}

	override fun mouseClickedInner(x: Double, y: Double, button: Int): Boolean {
		super.mouseClickedInner(x, y, button)
		requestFocus()
		return true
	}

	override fun keyPressedInternal(key: Int, scancode: Int, mods: Int): Boolean {
		if (key == InputConstants.KEY_ESCAPE && widget?.isActive == true) {
			widget?.isFocused = false
			return true
		}

		return super.keyPressedInternal(key, scancode, mods)
	}
}
