package ru.dbotthepony.mc.otm.client.render.blockentity

import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.renderer.MultiBufferSource
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider
import net.minecraft.network.chat.MutableComponent
import ru.dbotthepony.mc.otm.block.entity.decorative.HoloSignBlockEntity
import ru.dbotthepony.mc.otm.client.font
import ru.dbotthepony.mc.otm.client.render.DynamicBufferSource
import ru.dbotthepony.mc.otm.client.render.RenderGravity
import ru.dbotthepony.mc.otm.client.render.draw
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.core.math.BlockRotationFreedom
import ru.dbotthepony.kommons.math.RGBAColor
import ru.dbotthepony.mc.otm.client.MatteryGUI.SMALL_FONT_STYLE
import ru.dbotthepony.mc.otm.client.MatteryGUI.STANDARD_FONT_STYLE
import ru.dbotthepony.mc.otm.core.TextComponent
import ru.dbotthepony.mc.otm.core.math.rotateWithBlockFacing

class HoloSignRenderer(private val context: BlockEntityRendererProvider.Context) : BlockEntityRenderer<HoloSignBlockEntity> {
	override fun render(
		tile: HoloSignBlockEntity,
		partialTick: Float,
		poseStack: PoseStack,
		bufferSource: MultiBufferSource,
		p_112311_: Int,
		p_112312_: Int
	) {
		if (tile.redstoneControl.isBlockedByRedstone)
			return

		poseStack.pushPose()
		poseStack.rotateWithBlockFacing(tile.blockState[BlockRotationFreedom.DIRECTIONAL_WITH_ROTATION])
		poseStack.translate(0.5f, 0.5f, 0.75f)
		poseStack.scale(0.01f, 0.01f, 0.01f)

		val style = if (tile.smallerFont) SMALL_FONT_STYLE else STANDARD_FONT_STYLE
		val lines: List<MutableComponent> = tile.signText.split('\n').map { TextComponent(it).withStyle(style) }
		val totalHeight = lines.size * font.lineHeight + (lines.size - 1) * 2f
		var y = -totalHeight / 2f

		if (tile.textAutoScale) {
			val totalWidth = lines.maxOf { font.width(it) }.toFloat()
			val highest = totalWidth.coerceAtLeast(totalHeight)
			val mul = if (highest > 96f) 1f / (highest / 96f) else 96f / highest
			poseStack.scale(mul, mul, mul)
		}

		for (line in lines) {
			font.draw(poseStack = poseStack, buffer = bufferSource, text = line, gravity = RenderGravity.TOP_CENTER, y = y, color = RGBAColor(tile.textRed, tile.textGreen, tile.textBlue, tile.textAlpha))
			y += font.lineHeight + 2f
		}

		poseStack.popPose()
	}
}
