package ru.dbotthepony.mc.otm.client.screen.widget

import com.mojang.blaze3d.systems.RenderSystem
import com.mojang.blaze3d.vertex.PoseStack
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.render.UVWindingOrder
import ru.dbotthepony.mc.otm.client.render.WidgetLocation
import ru.dbotthepony.mc.otm.client.screen.panels.EditablePanel
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.menu.widget.ProgressGaugeWidget
import kotlin.math.roundToInt

open class ProgressGaugePanel<out S : Screen> @JvmOverloads constructor(
	screen: S,
	parent: EditablePanel<*>? = null,
	val widget: ProgressGaugeWidget,
	x: Float = 0f,
	y: Float = 0f
): EditablePanel<S>(screen, parent, x, y, width = GAUGE_BACKGROUND.width, height = GAUGE_BACKGROUND.height) {
	init {
		scissor = true
	}

	var flop = false

	protected open fun makeTooltip(): MutableList<Component> {
		val tooltip: MutableList<Component>

		if (widget.isStuck) {
			tooltip = mutableListOf(
				TranslatableComponent(
					"otm.gui.progress_widget",
					String.format("%.2f", widget.percentage * 100f)
				),
				TranslatableComponent("otm.gui.progress_widget_stuck").withStyle(ChatFormatting.DARK_RED)
			)
		} else {
			tooltip = mutableListOf(
				TranslatableComponent(
					"otm.gui.progress_widget",
					String.format("%.2f", widget.percentage * 100f)
				)
			)
		}

		return tooltip
	}

	override fun innerRender(graphics: GuiGraphics, mouseX: Float, mouseY: Float, partialTick: Float) {
		if (widget.isStuck && tickCount % 40 <= 20) {
			RenderSystem.setShaderColor(0.75f, 0.4f, 0.4f, 1f)
		}

		if (flop) {
			GAUGE_BACKGROUND.render(graphics, height = height, width = this.width, winding = UVWindingOrder.U1_V0_U0_V1)
			val width = (this.width * widget.percentage).roundToInt().toFloat()
			GAUGE_FOREGROUND.renderPartial(graphics, x = this.width - width, height = height, width = width, winding = UVWindingOrder.U1_V0_U0_V1)
		} else {
			GAUGE_BACKGROUND.render(graphics, height = height, width = this.width)
			val width = (this.width * widget.percentage).roundToInt().toFloat()
			GAUGE_FOREGROUND.renderPartial(graphics, height = height, width = width)
		}

		if (widget.isStuck && tickCount % 40 <= 20) {
			RenderSystem.setShaderColor(1f, 1f, 1f, 1f)
		}
	}

	override fun innerRenderTooltips(graphics: GuiGraphics, mouseX: Float, mouseY: Float, partialTick: Float): Boolean {
		if (isHovered) {
			graphics.renderComponentTooltip(font, makeTooltip(), mouseX.toInt(), mouseY.toInt())
			return true
		}

		return false
	}

	companion object {
		val GAUGE_BACKGROUND = WidgetLocation.PROGRESS_ARROWS.sprite(y = 0f, width = 22f, height = 15f)
		val GAUGE_FOREGROUND = WidgetLocation.PROGRESS_ARROWS.sprite(y = 15f, width = 22f, height = 15f)
	}
}
