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

import com.mojang.blaze3d.platform.InputConstants
import net.minecraft.client.gui.screens.Screen
import net.minecraft.network.chat.Component
import ru.dbotthepony.mc.otm.client.screen.MatteryScreen
import ru.dbotthepony.mc.otm.client.screen.panels.Dock
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import ru.dbotthepony.mc.otm.client.screen.panels.FramePanel
import ru.dbotthepony.mc.otm.client.screen.panels.Label
import ru.dbotthepony.mc.otm.client.screen.panels.button.ButtonPanel
import ru.dbotthepony.mc.otm.core.TranslatableComponent

open class QueryUserPanel<out S: Screen>(
	screen: S,
	title: Component,
	description: Collection<Component>,
	protected val onConfirm: Runnable?,
	protected val onCancel: Runnable? = null,
) : FramePanel<S>(screen, 100f, 10f, title) {
	protected val description: MutableList<Label<@UnsafeVariance S>> = ArrayList()

	init {
		if (screen is MatteryScreen<*>) {
			screen.addPanel(this as EditablePanel<MatteryScreen<*>>)
		}

		dockPadding = dockPadding.copy(top = PADDING_TOP + 4f)

		var maxWidth = font.width(title) + PADDING * 2f
		var height = 0f

		for (line in description) {
			Label(screen, this, text = line).also {
				it.dock = Dock.TOP
				height += it.height
				this.description.add(it)
			}

			maxWidth = maxWidth.coerceAtLeast(font.width(line).toFloat())
		}

		val bottom = EditablePanel(screen, this, height = ButtonPanel.HEIGHT)
		bottom.dock = Dock.BOTTOM

		this.height = height + bottom.height + PADDING + PADDING_TOP + 4f

		ButtonPanel(screen, bottom, width = font.width(TranslatableComponent("otm.gui.cancel")) + 12f, label = TranslatableComponent("otm.gui.cancel"), onPress = Runnable {
			onCancel?.run()
			this.remove()
		}).dock = Dock.RIGHT

		if (onConfirm != null) {
			ButtonPanel(screen, bottom, width = font.width(TranslatableComponent("otm.gui.confirm")) + 12f, label = TranslatableComponent("otm.gui.confirm"), onPress = Runnable {
				onConfirm.run()
				this.remove()
			}).also {
				it.dock = Dock.RIGHT
				it.dockRight = 2f
			}
		}

		this.width = maxWidth.coerceAtLeast(bottom.children.stream().mapToDouble { it.width.toDouble() }.sum().toFloat() + 2f) + PADDING * 2f

		toScreenCenter()
		behaveAsWindow()
	}

	override fun keyPressedInternal(key: Int, scancode: Int, mods: Int): Boolean {
		if (key == InputConstants.KEY_ESCAPE) {
			onCancel?.run()
			remove()
			return true
		}

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