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

import com.mojang.blaze3d.platform.InputConstants
import net.minecraft.client.gui.screens.Screen
import ru.dbotthepony.mc.otm.client.render.AbstractMatterySprite
import ru.dbotthepony.mc.otm.client.render.Widgets
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.button.RectangleButtonPanel

open class HeightControls<out S : Screen>(
	screen: S,
	parent: EditablePanel<*>?,
	x: Float = 0f,
	y: Float = 0f,
	val callback: (isIncrease: Boolean) -> Status
) : BackgroundPanel<S>(screen, parent, x, y, WIDTH, HEIGHT) {
	enum class Status(val canIncrease: Boolean, val canDecrease: Boolean) {
		NONE(false, false),
		INCREASE(true, false),
		DECREASE(false, true),
		EITHER(true, true);

		companion object {
			fun of(canIncrease: Boolean, canDecrease: Boolean): Status {
				return if (canIncrease && canDecrease) {
					EITHER
				} else if (canIncrease) {
					INCREASE
				} else if (canDecrease) {
					DECREASE
				} else {
					NONE
				}
			}
		}
	}

	var controlStatus: Status = Status.EITHER
		set(value) {
			if (field == value)
				return

			field = value
			increase.isDisabled = !value.canIncrease
			decrease.isDisabled = !value.canDecrease
		}

	open inner class Control(val isIncrease: Boolean) : RectangleButtonPanel<S>(screen, this@HeightControls, width = BUTTON_WIDTH, height = BUTTON_HEIGHT) {
		override val PRESSED: AbstractMatterySprite = if (isIncrease) Widgets.ARROW_DOWN_BUTTON_PRESSED else Widgets.ARROW_UP_BUTTON_PRESSED
		override val HOVERED: AbstractMatterySprite = if (isIncrease) Widgets.ARROW_DOWN_BUTTON_HOVERED else Widgets.ARROW_UP_BUTTON_HOVERED
		override val IDLE: AbstractMatterySprite = if (isIncrease) Widgets.ARROW_DOWN_BUTTON_IDLE else Widgets.ARROW_UP_BUTTON_IDLE
		override val DISABLED: AbstractMatterySprite = if (isIncrease) Widgets.ARROW_DOWN_BUTTON_DISABLED else Widgets.ARROW_UP_BUTTON_DISABLED

		init {
			dock = Dock.TOP
			dockBottom = 2f
		}

		override fun onClick(clickButton: Int) {
			if (clickButton == InputConstants.MOUSE_BUTTON_LEFT) {
				this@HeightControls.onClick(isIncrease)
			} else if (clickButton == InputConstants.MOUSE_BUTTON_RIGHT) {
				this@HeightControls.onClick(!isIncrease)
			}
		}
	}

	val decrease = Control(false)
	val increase = Control(true)

	open fun onClick(isIncrease: Boolean) {
		controlStatus = callback.invoke(isIncrease)
	}

	companion object {
		const val BUTTON_WIDTH = 18f
		const val BUTTON_HEIGHT = 6f
		const val WIDTH = BUTTON_WIDTH + 4f
		const val HEIGHT = BUTTON_HEIGHT * 2f + 8f
	}
}
