package ru.dbotthepony.mc.otm.block.decorative

import net.minecraft.core.BlockPos
import net.minecraft.world.InteractionResult
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.DyeColor
import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.material.MapColor
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.addSimpleDescription
import ru.dbotthepony.mc.otm.block.getShapeForEachState
import ru.dbotthepony.mc.otm.core.AABB
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.core.math.BlockRotationFreedom
import ru.dbotthepony.mc.otm.core.math.plus
import ru.dbotthepony.mc.otm.entity.RideableDummy
import ru.dbotthepony.mc.otm.shapes.BlockShapes

class StarChairBlock(val color: DyeColor?) : RotatableMatteryBlock(DEFAULT_PROPERTIES.mapColor(color?.mapColor ?: MapColor.COLOR_LIGHT_BLUE)) {

	override fun rotationFreedom(): BlockRotationFreedom = BlockRotationFreedom.HORIZONTAL

	init {
		addSimpleDescription()
	}

	private val shapes = getShapeForEachState(rotationProperty) { BlockShapes.STAR_CHAIR.rotateFromNorth(it[rotationProperty]).computeShape() }
	override fun getShape(state: BlockState, blockGetter: BlockGetter, pos: BlockPos, context: CollisionContext): VoxelShape = shapes[state]!!

	override fun useWithoutItem(blockState: BlockState, level: Level, blockPos: BlockPos, ply: Player, blockHitResult: BlockHitResult): InteractionResult {
		if (ply.isCrouching) return super.useWithoutItem(blockState, level, blockPos, ply, blockHitResult)
		if (level.isClientSide) return InteractionResult.SUCCESS

		val entities = level.getEntitiesOfClass(RideableDummy::class.java, AABB(blockPos, blockPos + BlockPos(1, 1, 1)))
		if (entities.isNotEmpty()) return InteractionResult.FAIL

		val entity = RideableDummy(level, blockPos, blockState)

		entity.yRot = blockState[rotationFreedom()].front.toYRot()
		entity.setPos(blockPos.x + 0.5, blockPos.y.toDouble(), blockPos.z + 0.5)

		level.addFreshEntity(entity)
		ply.startRiding(entity)

		return InteractionResult.SUCCESS
	}
}
