package ru.dbotthepony.mc.otm.block.tech

import net.minecraft.core.BlockPos
import net.minecraft.world.item.crafting.AbstractCookingRecipe
import net.minecraft.world.item.crafting.RecipeType
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.EntityBlock
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.entity.BlockEntityTicker
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.Shapes
import net.minecraft.world.phys.shapes.VoxelShape
import ru.dbotthepony.mc.otm.block.RotatableMatteryBlock
import ru.dbotthepony.mc.otm.block.entity.WorkerState
import ru.dbotthepony.mc.otm.block.entity.tech.PoweredFurnaceBlockEntity
import ru.dbotthepony.mc.otm.block.getShapeForEachState
import ru.dbotthepony.mc.otm.config.WorkerBalanceValues
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.shapes.BlockShape

class PoweredFurnaceBlock(
	val type: () -> BlockEntityType<PoweredFurnaceBlockEntity>,
	val recipeType: RecipeType<out AbstractCookingRecipe>,
	val config: WorkerBalanceValues,
	shape: BlockShape?
) : RotatableMatteryBlock(), EntityBlock {
	override fun newBlockEntity(p_153215_: BlockPos, p_153216_: BlockState): PoweredFurnaceBlockEntity {
		return PoweredFurnaceBlockEntity(type.invoke(), p_153215_, p_153216_, recipeType, config)
	}

	override fun createBlockStateDefinition(builder: StateDefinition.Builder<Block, BlockState>) {
		super.createBlockStateDefinition(builder)
		builder.add(WorkerState.WORKER_STATE)
	}

	private val shapes = getShapeForEachState(rotationProperty) {
		shape?.rotateFromNorth(it[rotationProperty])?.computeShape() ?: Shapes.block()
	}

	@Suppress("override_deprecation")
	override fun getShape(
		state: BlockState,
		blockGetter: BlockGetter,
		pos: BlockPos,
		context: CollisionContext
	): VoxelShape {
		return shapes[state]!!
	}

	override fun <T : BlockEntity?> getTicker(p_153212_: Level, p_153213_: BlockState, p_153214_: BlockEntityType<T>): BlockEntityTicker<T>? {
		if (p_153212_.isClientSide)
			return null

		return BlockEntityTicker { _, _, _, tile -> if (tile is PoweredFurnaceBlockEntity) tile.tick() }
	}
}
