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

import com.mojang.blaze3d.platform.InputConstants
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.client.gui.screens.Screen
import ru.dbotthepony.mc.otm.client.playGuiClickSound
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import java.util.function.IntPredicate

abstract class AbstractButtonPanel<out S : Screen>(
	screen: S,
	parent: EditablePanel<*>?,
	x: Float = 0f,
	y: Float = 0f,
	width: Float = 10f,
	height: Float = 10f,
) : EditablePanel<S>(screen, parent, x, y, width, height), IntPredicate {
	var isPressed = false
		protected set

	open var isDisabled = false
		set(value) {
			if (field != value) {
				if (!value) {
					isPressed = false
					grabMouseInput = false
				}

				field = value
			}
		}

	override fun test(value: Int): Boolean {
		return value == InputConstants.MOUSE_BUTTON_LEFT
	}

	abstract fun onClick(mouseButton: Int)

	override fun mouseClickedInner(x: Double, y: Double, button: Int): Boolean {
		if (isDisabled || isPressed || !test(button)) {
			return true
		}

		if (!tryToGrabMouseInput()) {
			return true
		}

		isPressed = true
		playGuiClickSound()
		return true
	}

	override fun mouseReleasedInner(x: Double, y: Double, button: Int): Boolean {
		if (!isPressed || !test(button)) {
			return true
		}

		grabMouseInput = false
		isPressed = false

		if (isHovered) {
			onClick(button)
		}

		return true
	}

	override fun shouldRenderTooltips(graphics: GuiGraphics, mouseX: Float, mouseY: Float, partialTick: Float): Boolean {
		return super.shouldRenderTooltips(graphics, mouseX, mouseY, partialTick) || isPressed
	}
}
