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

import com.mojang.blaze3d.platform.GlStateManager
import com.mojang.blaze3d.systems.RenderSystem
import com.mojang.blaze3d.vertex.PoseStack
import com.mojang.math.Axis
import net.minecraft.client.renderer.MultiBufferSource
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider
import net.minecraft.world.item.ItemDisplayContext
import ru.dbotthepony.mc.otm.block.entity.matter.MatterScannerBlockEntity
import ru.dbotthepony.mc.otm.client.render.DynamicBufferSource
import ru.dbotthepony.mc.otm.client.render.lockBlendFunc

class MatterScannerRenderer(private val context: BlockEntityRendererProvider.Context) : BlockEntityRenderer<MatterScannerBlockEntity> {
	companion object {
		private val source = DynamicBufferSource(maximalInitialBufferSize = 2 shl 10)
	}

	override fun render(
		tile: MatterScannerBlockEntity,
		partialTick: Float,
		pose: PoseStack,
		bufferSource: MultiBufferSource,
		packedLight: Int,
		packedOverlay: Int
	) {
		val item = tile.visualItemStack

		if (item.isEmpty) {
			return
		}

		pose.pushPose()

		pose.translate(0.5, 0.5, 0.5)
		pose.scale(0.5f, 0.5f, 0.5f)

		pose.mulPose(Axis.XP.rotationDegrees(90f))
		pose.mulPose(Axis.ZP.rotationDegrees(tile.blockRotation.back.toYRot()))

		context.itemRenderer.renderStatic(
			item,
			ItemDisplayContext.FIXED,
			packedLight,
			packedOverlay,
			pose,
			source,
			tile.level,
			tile.blockPos.asLong().toInt()
		)

		RenderSystem.enableBlend()
		RenderSystem.setShaderColor(1f, 1f, 1f, 1f - tile.visualProgress)
		RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA)

		lockBlendFunc = true

		try {
			source.endBatch()
		} finally {
			lockBlendFunc = false
		}

		RenderSystem.disableBlend()
		RenderSystem.defaultBlendFunc()
		RenderSystem.setShaderColor(1f, 1f, 1f, 1f)

		pose.popPose()
	}
}
