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

import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.screens.Screen
import net.minecraft.network.chat.Component
import ru.dbotthepony.mc.otm.client.render.RenderGravity
import ru.dbotthepony.mc.otm.client.render.Widgets18
import ru.dbotthepony.mc.otm.client.render.drawAligned
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import ru.dbotthepony.mc.otm.core.math.RGBAColor
import java.util.function.IntConsumer

open class ButtonPanel<out S : Screen>(
	screen: S,
	parent: EditablePanel<*>?,
	x: Float = 0f,
	y: Float = 0f,
	width: Float = 40f,
	height: Float = HEIGHT,
	var label: Component,
	var onPress: IntConsumer? = null
) : AbstractButtonPanel<S>(screen, parent, x, y, width, height) {
	constructor(screen: S, parent: EditablePanel<*>?, label: Component, onPress: IntConsumer? = null) : this(screen, parent, x = 0f, label = label, onPress = onPress)

	constructor(
		screen: S,
		parent: EditablePanel<*>?,
		x: Float = 0f,
		y: Float = 0f,
		width: Float = 40f,
		height: Float = HEIGHT,
		label: Component,
		onPress: Runnable
	) : this(screen, parent, x, y, width, height, label, onPress = IntConsumer { onPress.run() })

	var textColor = RGBAColor.WHITE

	override fun onClick(mouseButton: Int) {
		onPress?.accept(mouseButton)
	}

	protected fun renderStretchableBackground(graphics: GuiGraphics, mouseX: Float, mouseY: Float, partialTick: Float) {
		if (isDisabled) {
			Widgets18.BUTTON_DISABLED_STRETCHABLE.render(graphics, width = width, height = height)
		} else if (isPressed) {
			Widgets18.BUTTON_PRESSED_STRETCHABLE.render(graphics, width = width, height = height)
		} else if (isHovered) {
			Widgets18.BUTTON_HOVERED_STRETCHABLE.render(graphics, width = width, height = height)
		} else {
			Widgets18.BUTTON_IDLE_STRETCHABLE.render(graphics, width = width, height = height)
		}
	}

	override fun innerRender(graphics: GuiGraphics, mouseX: Float, mouseY: Float, partialTick: Float) {
		renderStretchableBackground(graphics, mouseX, mouseY, partialTick)
		graphics.drawAligned(font, label, RenderGravity.CENTER_CENTER, width / 2f, height / 2f, textColor.toRGB())
	}

	override fun sizeToContents() {
		super.sizeToContents()

		height = height.coerceAtLeast(HEIGHT).coerceAtLeast(font.lineHeight.toFloat() + 2f)
		width = width.coerceAtLeast(HEIGHT).coerceAtLeast(font.width(label) + 4f)
	}

	companion object {
		const val HEIGHT = 18f
	}
}
