package ru.dbotthepony.mc.otm.block.storage

import net.minecraft.core.BlockPos
import net.minecraft.network.chat.Component
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.TooltipFlag
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.Level
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.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.VoxelShape
import ru.dbotthepony.mc.otm.block.RotatableMatteryBlock
import ru.dbotthepony.mc.otm.block.entity.MatteryPoweredBlockEntity
import ru.dbotthepony.mc.otm.block.entity.storage.DriveRackBlockEntity
import ru.dbotthepony.mc.otm.block.getShapeForEachState
import ru.dbotthepony.mc.otm.capability.energy.WorkerEnergyStorage
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.registry.MBlockEntities
import ru.dbotthepony.mc.otm.shapes.BlockShapes

class DriveRackBlock : RotatableMatteryBlock(DEFAULT_MACHINE_PROPERTIES), EntityBlock {
	override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): BlockEntity {
		return DriveRackBlockEntity(blockPos, blockState)
	}

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

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

	override fun appendHoverText(
		itemStack: ItemStack,
		blockAccessor: BlockGetter?,
		components: MutableList<Component>,
		tooltipType: TooltipFlag
	) {
		super.appendHoverText(itemStack, blockAccessor, components, tooltipType)
		WorkerEnergyStorage.appendHoverText(itemStack, blockAccessor, components, tooltipType)
		MatteryPoweredBlockEntity.appendHoverText(itemStack, blockAccessor, components, tooltipType)
	}

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

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