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

import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.world.item.context.BlockPlaceContext
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.level.block.state.properties.BooleanProperty
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.WorkerState
import ru.dbotthepony.mc.otm.block.entity.matter.MatterBottlerBlockEntity
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 MatterBottlerBlock : RotatableMatteryBlock(), EntityBlock {
	override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): BlockEntity? {
		return MatterBottlerBlockEntity(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_BOTTLER)
			return null

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

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

	override fun getStateForPlacement(context: BlockPlaceContext): BlockState {
		return super.getStateForPlacement(context)!!
			.setValue(SLOT_PROPERTIES[0], false)
			.setValue(SLOT_PROPERTIES[1], false)
			.setValue(SLOT_PROPERTIES[2], false)
	}

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

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

	companion object {
		val SLOT_PROPERTIES = arrayOf(
			BooleanProperty.create("bottle_0"),
			BooleanProperty.create("bottle_1"),
			BooleanProperty.create("bottle_2")
		)
	}
}
