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

import net.minecraft.core.BlockPos
import net.minecraft.world.InteractionHand
import net.minecraft.world.InteractionResult
import net.minecraft.world.entity.player.Player
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.BlockHitResult
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.tech.EssenceStorageBlockEntity
import ru.dbotthepony.mc.otm.block.getShapeForEachState
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.registry.MItems
import ru.dbotthepony.mc.otm.shapes.BlockShapes

class EssenceStorageBlock : RotatableMatteryBlock(), EntityBlock {
	override fun newBlockEntity(pPos: BlockPos, pState: BlockState): BlockEntity {
		return EssenceStorageBlockEntity(pPos, pState)
	}

	override fun <T : BlockEntity?> getTicker(pLevel: Level, pState: BlockState, pBlockEntityType: BlockEntityType<T>): BlockEntityTicker<T>? {
		if (!pLevel.isClientSide) {
			return BlockEntityTicker { _, _, _, pBlockEntity -> if (pBlockEntity is EssenceStorageBlockEntity) pBlockEntity.tick() }
		}

		return null
	}

	@Suppress("OVERRIDE_DEPRECATION")
	override fun use(blockState: BlockState, level: Level, blockPos: BlockPos, ply: Player, hand: InteractionHand, blockHitResult: BlockHitResult): InteractionResult {
		if (ply.getItemInHand(hand).item == MItems.ESSENCE_SERVO) {
			return MItems.ESSENCE_SERVO.useServo(ply, blockPos)
		}

		return super.use(blockState, level, blockPos, ply, hand, blockHitResult)
	}

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

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