package ru.dbotthepony.mc.otm.block

import net.minecraft.core.Direction
import net.minecraft.world.item.context.BlockPlaceContext
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Rotation
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.core.math.BlockRotation
import ru.dbotthepony.mc.otm.core.math.BlockRotationFreedom

abstract class RotatableMatteryBlock @JvmOverloads constructor(properties: Properties = DEFAULT_PROPERTIES) : MatteryBlock(properties) {
	init {
		@Suppress("LeakingThis")
		registerDefaultState(getStateDefinition().any().setValue(rotationProperty, BlockRotation.SOUTH))
	}

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

	override fun getStateForPlacement(context: BlockPlaceContext): BlockState? {
		return when (val freedom = rotationFreedom()) {
			BlockRotationFreedom.ONE -> defaultBlockState().setValue(
				freedom.property,
				freedom.of(if (faceToPlayer(context)) context.horizontalDirection.opposite else context.horizontalDirection)
			)

			BlockRotationFreedom.TWO -> defaultBlockState().setValue(
				freedom.property,
				freedom.of(if (faceToPlayer(context)) context.nearestLookingDirection.opposite else context.nearestLookingDirection)
			)

			BlockRotationFreedom.THREE -> {
				val primary = if (faceToPlayer(context)) context.nearestLookingDirection.opposite else context.nearestLookingDirection
				var secondary = if (faceToPlayer(context)) context.horizontalDirection else context.horizontalDirection.opposite

				if (primary == Direction.DOWN) {
					secondary = secondary.opposite
				}

				defaultBlockState().setValue(
					freedom.property,
					freedom.of(primary, secondary)
				)
			}

			BlockRotationFreedom.FOUR -> TODO("Can't rotate with four rotation freedom yet")
		}
	}

	@Suppress("OVERRIDE_DEPRECATION")
	override fun rotate(blockState: BlockState, rotation: Rotation): BlockState {
		@Suppress("DEPRECATION")
		return super.rotate(blockState, rotation).setValue(rotationProperty, blockState[rotationProperty].rotate(rotation))
	}

	val rotationProperty get() = rotationFreedom().property

	open fun rotationFreedom(): BlockRotationFreedom {
		return BlockRotationFreedom.ONE
	}

	open fun faceToPlayer(context: BlockPlaceContext): Boolean {
		return true
	}
}
