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.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 net.minecraftforge.fluids.FluidUtil
import ru.dbotthepony.mc.otm.block.RotatableMatteryBlock
import ru.dbotthepony.mc.otm.block.entity.decorative.FluidTankBlockEntity
import ru.dbotthepony.mc.otm.block.getShapeForEachState
import ru.dbotthepony.mc.otm.core.get
import ru.dbotthepony.mc.otm.shapes.BlockShapes

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

	override fun <T : BlockEntity?> getTicker(pLevel: Level, pState: BlockState, pBlockEntityType: BlockEntityType<T>): BlockEntityTicker<T>? {
		if (pLevel.isClientSide)
			return null

		return BlockEntityTicker { _, _, _, pBlockEntity -> if (pBlockEntity is FluidTankBlockEntity) pBlockEntity.tick() }
	}

	@Suppress("OVERRIDE_DEPRECATION")
	override fun use(blockState: BlockState, level: Level, blockPos: BlockPos, ply: Player, hand: InteractionHand, blockHitResult: BlockHitResult): InteractionResult {
		if (FluidUtil.interactWithFluidHandler(ply, hand, level, blockPos, blockHitResult.direction)) {
			return InteractionResult.sidedSuccess(level.isClientSide)
		}

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

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

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

	override fun getLightEmission(state: BlockState?, level: BlockGetter?, pos: BlockPos?): Int {
		if (pos == BlockPos.ZERO) return 15

		val lightLevel = super.getLightEmission(state, level, pos)

		val tile = level?.getExistingBlockEntity(pos) ?: lightLevel

		if (tile is FluidTankBlockEntity) {
			val fluid = tile.synchronizedFluid

			if (!fluid.isEmpty) {
				val newLevel = fluid.fluid.fluidType.getLightLevel(fluid)
				return newLevel.coerceAtLeast(lightLevel)
			}
		}

		return lightLevel
	}
}
