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

import net.minecraft.world.level.block.EntityBlock
import net.minecraft.core.BlockPos
import net.minecraft.world.item.DyeColor
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.entity.BlockEntity
import ru.dbotthepony.mc.otm.block.entity.matter.MatterDecomposerBlockEntity
import net.minecraft.world.level.block.entity.BlockEntityType
import net.minecraft.world.level.block.entity.BlockEntityTicker
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block
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.addSimpleDescription
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.registry.game.MBlockEntities
import ru.dbotthepony.mc.otm.shapes.BlockShapes

class MatterDecomposerBlock(val color: DyeColor?) : RotatableMatteryBlock(DEFAULT_MACHINE_PROPERTIES), EntityBlock {
	init {
		tooltips.colored(color)
		addSimpleDescription()
		tooltips.blockEntityEnergy()
		tooltips.blockEntityMatter()
	}

	override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): BlockEntity {
		return MatterDecomposerBlockEntity(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_DECOMPOSER)
			return null

		return BlockEntityTicker {_, _, _, t -> if (t is MatterDecomposerBlockEntity) t.tick()}
	}

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

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

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