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

import net.minecraft.core.BlockPos
import net.minecraft.world.InteractionHand
import net.minecraft.world.InteractionResult
import net.minecraft.world.ItemInteractionResult
import net.minecraft.world.entity.player.Player
import net.minecraft.world.item.ItemStack
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.level.material.MapColor
import net.minecraft.world.level.material.PushReaction
import net.minecraft.world.phys.BlockHitResult
import net.minecraft.world.phys.shapes.CollisionContext
import net.minecraft.world.phys.shapes.VoxelShape
import net.neoforged.neoforge.fluids.FluidUtil
import ru.dbotthepony.mc.otm.block.RotatableMatteryBlock
import ru.dbotthepony.mc.otm.block.addSimpleDescription
import ru.dbotthepony.mc.otm.block.entity.decorative.InfiniteWaterSourceBlockEntity
import ru.dbotthepony.mc.otm.block.getShapeForEachState
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.shapes.BlockShapes

class InfiniteWaterSourceBlock : RotatableMatteryBlock(
	Properties.of()
		.destroyTime(1.5f)
		.explosionResistance(10f)
		.pushReaction(PushReaction.NORMAL)
		.requiresCorrectToolForDrops()
		.mapColor(MapColor.WATER)
		.forceSolidOff()
		.noOcclusion()
), EntityBlock {
	override fun newBlockEntity(p_153215_: BlockPos, p_153216_: BlockState): BlockEntity {
		return InfiniteWaterSourceBlockEntity(p_153215_, p_153216_)
	}

	init {
		addSimpleDescription()
	}

	override fun useItemOn(
		p_316304_: ItemStack,
		p_316362_: BlockState,
		p_316459_: Level,
		p_316366_: BlockPos,
		p_316132_: Player,
		p_316595_: InteractionHand,
		p_316140_: BlockHitResult
	): ItemInteractionResult {
		if (FluidUtil.interactWithFluidHandler(p_316132_, p_316595_, p_316459_, p_316366_, p_316140_.direction)) {
			return ItemInteractionResult.sidedSuccess(p_316459_.isClientSide)
		}

		return super.useItemOn(p_316304_, p_316362_, p_316459_, p_316366_, p_316132_, p_316595_, p_316140_)
	}

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

		return BlockEntityTicker { _, _, _, p_155256_ -> if (p_155256_ is InfiniteWaterSourceBlockEntity) p_155256_.tick() }
	}

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

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