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

import net.minecraft.ChatFormatting
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.minecraft
import ru.dbotthepony.mc.otm.client.render.IGUIRenderable
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import ru.dbotthepony.mc.otm.core.GetterSetter
import ru.dbotthepony.mc.otm.core.TextComponent
import ru.dbotthepony.mc.otm.core.value
import ru.dbotthepony.mc.otm.menu.input.IPlayerInputWithFeedback

abstract class BooleanRectangleButtonPanel<out S : Screen>(
	screen: S,
	parent: EditablePanel<*>?,
	x: Float = 0f,
	y: Float = 0f,
	width: Float,
	height: Float,
	val prop: GetterSetter<Boolean>,
	var skinElementActive: IGUIRenderable? = null,
	var skinElementInactive: IGUIRenderable? = null,
	val onChange: ((newValue: Boolean) -> Unit)? = null,
	var tooltipActive: Component? = null,
	var tooltipInactive: Component? = null,
) : RectangleButtonPanel<S>(screen, parent, x, y, width, height, null) {
	override fun onClick(mouseButton: Int) {
		val newValue = !prop.value
		prop.value = newValue
		onChange?.invoke(newValue)
	}

	override fun innerRenderTooltips(graphics: GuiGraphics, mouseX: Float, mouseY: Float, partialTick: Float): Boolean {
		if (isHovered) {
			val tooltipActive = tooltipActive
			val tooltipInactive = tooltipInactive

			if (tooltipActive != null || tooltipInactive != null || tooltips.isNotEmpty()) {
				val tooltips = ArrayList<Component>(2 + this.tooltips.size)

				if (this.tooltips.isNotEmpty()) {
					tooltips.addAll(this.tooltips)

					if (tooltipActive != null || tooltipInactive != null)
						tooltips.add(SPACE)
				}

				if (tooltipActive != null) {
					tooltips.add(tooltipActive.copy().withStyle(if (prop.get()) ChatFormatting.WHITE else ChatFormatting.GRAY))
				}

				if (tooltipInactive != null) {
					tooltips.add(tooltipInactive.copy().withStyle(if (!prop.get()) ChatFormatting.WHITE else ChatFormatting.GRAY))
				}

				graphics.renderComponentTooltip(font, tooltips, mouseX.toInt(), mouseY.toInt())
			}
		}

		return super.innerRenderTooltips(graphics, mouseX, mouseY, partialTick)
	}

	override var isDisabled: Boolean
		get() {
			if (prop is IPlayerInputWithFeedback<Boolean>) {
				return !prop.test(minecraft.player)
			} else {
				return super.isDisabled
			}
		}
		set(value) { super.isDisabled = value }

	override fun innerRender(graphics: GuiGraphics, mouseX: Float, mouseY: Float, partialTick: Float) {
		super.innerRender(graphics, mouseX, mouseY, partialTick)

		if (prop.value) {
			skinElementActive?.render(graphics, width = width, height = height)
		} else {
			skinElementInactive?.render(graphics, width = width, height = height)
		}
	}

	companion object {
		private val SPACE = TextComponent("")
	}
}
