package ru.dbotthepony.mc.otm.block.matter

import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
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.VoxelShape
import ru.dbotthepony.mc.otm.block.RotatableMatteryBlock
import ru.dbotthepony.mc.otm.block.entity.matter.MatterReplicatorBlockEntity
import ru.dbotthepony.mc.otm.block.entity.WorkerState
import ru.dbotthepony.mc.otm.block.getShapeForEachState
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.core.math.facingOne
import ru.dbotthepony.mc.otm.registry.MBlockEntities
import ru.dbotthepony.mc.otm.shapes.BlockShapes

class MatterReplicatorBlock : RotatableMatteryBlock(), EntityBlock {
	override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): BlockEntity {
		return MatterReplicatorBlockEntity(blockPos, blockState)
	}

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

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

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

	private val shapes = getShapeForEachState(rotationProperty) { BlockShapes.MATTER_REPLICATOR.rotateFromNorth(it[rotationProperty]).computeShape() }

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