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.world.item.ItemDisplayContext
import ru.dbotthepony.mc.otm.block.entity.tech.AbstractPoweredFurnaceBlockEntity
import ru.dbotthepony.mc.otm.core.math.normalizeAngle
import ru.dbotthepony.mc.otm.core.math.rotateY
import ru.dbotthepony.mc.otm.core.math.yRotationNorth
import ru.dbotthepony.mc.otm.core.math.yRotationSouth

class PoweredSmokerRenderer(private val context: BlockEntityRendererProvider.Context) : BlockEntityRenderer<AbstractPoweredFurnaceBlockEntity<*, *>> {
	override fun render(tile: AbstractPoweredFurnaceBlockEntity<*, *>, partialTick: Float, pose: PoseStack, buffers: MultiBufferSource, packedLight: Int, packedOverlay: Int) {
		val diff = System.nanoTime() - tile.lastRender
		tile.lastRender = System.nanoTime()

		for (slot in tile.syncSlots) {
			if (slot.inputItem.isEmpty && slot.outputItem.isEmpty) continue
			slot.visualRotation = normalizeAngle(slot.visualRotation + diff / 400_000_000f)

			pose.pushPose()
			pose.translate(0.5f, 0.5f, 0.5f)
			pose.rotateY(tile.blockRotation.front.yRotationNorth())
			pose.translate(-0.5f, -0.5f, -0.5f)
			pose.translate(0.625f, 0.5f, 0.5f)
			pose.scale(0.25f, 0.25f, 0.25f)

			pose.rotateY(slot.visualRotation)

			if (slot.progress <= 0.8f && !slot.inputItem.isEmpty) {
				val model = context.itemRenderer.getModel(
					slot.inputItem,
					tile.level,
					null,
					0
				)

				context.itemRenderer.render(
					slot.inputItem,
					ItemDisplayContext.NONE,
					false,
					pose,
					buffers,
					packedLight,
					packedOverlay,
					model
				)
			} else if (slot.progress > 0.8f && !slot.outputItem.isEmpty) {
				val model = context.itemRenderer.getModel(
					slot.outputItem,
					tile.level,
					null,
					0
				)

				context.itemRenderer.render(
					slot.outputItem,
					ItemDisplayContext.NONE,
					false,
					pose,
					buffers,
					packedLight,
					packedOverlay,
					model
				)
			}

			pose.popPose()
			break
		}
	}
}
