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

import net.minecraft.core.BlockPos
import net.minecraft.core.SectionPos
import net.minecraft.world.item.context.BlockPlaceContext
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.EntityBlock
import net.minecraft.world.level.block.SoundType
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 ru.dbotthepony.mc.otm.block.RotatableMatteryBlock
import ru.dbotthepony.mc.otm.block.entity.blackhole.BlackHoleBlockEntity
import ru.dbotthepony.mc.otm.block.entity.blackhole.BlackHoleGeneratorBlockEntity
import ru.dbotthepony.mc.otm.core.math.BlockRotationFreedom
import ru.dbotthepony.mc.otm.core.math.plus
import ru.dbotthepony.mc.otm.core.math.times

class BlackHoleGeneratorBlock : RotatableMatteryBlock(Properties.of().mapColor(MapColor.METAL).sound(SoundType.NETHERITE_BLOCK).requiresCorrectToolForDrops().destroyTime(2.5f).explosionResistance(160.0f)), EntityBlock {
	override fun newBlockEntity(blockPos: BlockPos, blockState: BlockState): BlockEntity {
		return BlackHoleGeneratorBlockEntity(blockPos, blockState)
	}

	override fun <T : BlockEntity?> getTicker(level: Level, blockState: BlockState, blockEntityType: BlockEntityType<T>): BlockEntityTicker<T>? {
		if (level.isClientSide)
			return null

		return BlockEntityTicker { _, _, _, tile -> if (tile is BlackHoleGeneratorBlockEntity) tile.tick() }
	}

	override fun getStateForPlacement(context: BlockPlaceContext): BlockState? {
		var state = super.getStateForPlacement(context) ?: return null
		val blockPos = context.clickedPos
		val level = context.level

		for (face in BlockRotationFreedom.HORIZONTAL.possibleValues) {
			val dir = face.normal

			for (i in 4 ..64) {
				val pos = blockPos + dir * i
				val chunk = level.chunkSource.getChunkNow(SectionPos.blockToSectionCoord(pos.x), SectionPos.blockToSectionCoord(pos.z)) ?: continue
				val getState = chunk.getBlockState(pos)

				if (!getState.isAir) {
					if (chunk.getBlockEntity(pos) is BlackHoleBlockEntity) {
						state = state.setValue(BlockRotationFreedom.HORIZONTAL.property, face)
						break
					}
				}
			}
		}

		return state
	}
}
