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

import net.minecraft.core.BlockPos
import net.minecraft.core.SectionPos
import net.minecraft.network.chat.Component
import net.minecraft.world.entity.player.Inventory
import net.minecraft.world.entity.player.Player
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.phys.AABB
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.block.tech.BlockGravitationStabilizerLens
import ru.dbotthepony.mc.otm.block.entity.MatteryDeviceBlockEntity
import ru.dbotthepony.mc.otm.block.entity.WorkerState
import ru.dbotthepony.mc.otm.block.entity.blackhole.BlackHoleBlockEntity
import ru.dbotthepony.mc.otm.block.tech.BlockGravitationStabilizer
import ru.dbotthepony.mc.otm.core.math.facingTwo
import ru.dbotthepony.mc.otm.core.math.plus
import ru.dbotthepony.mc.otm.core.math.times
import ru.dbotthepony.mc.otm.registry.MBlockEntities

class GravitationStabilizerBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : MatteryDeviceBlockEntity(MBlockEntities.GRAVITATION_STABILIZER, p_155229_, p_155230_) {
	override fun createMenu(containerID: Int, inventory: Inventory, ply: Player) = null

	private var blackHole: BlackHoleBlockEntity? = null

	fun tick(level: Level) {
		var findBlackHole: BlackHoleBlockEntity? = null
		val dir = blockState.facingTwo.normal

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

			if (!state.isAir) {
				val tile = chunk.getBlockEntity(pos)

				if (tile != null) {
					if (tile is BlackHoleBlockEntity) {
						findBlackHole = tile
					}

					break
				}

				if (state.isViewBlocking(level, pos)) {
					break
				}
			}
		}

		if (findBlackHole != blackHole) {
			blackHole?.stabilizerDetached(this)
			findBlackHole?.stabilizerAttached(this)
			blackHole = findBlackHole

			level.setBlock(blockPos, blockState.setValue(WorkerState.SEMI_WORKER_STATE, if (findBlackHole != null) WorkerState.WORKING else WorkerState.IDLE), Block.UPDATE_CLIENTS)
			val posLens = BlockGravitationStabilizer.getBoundingBlockPos(blockState, blockPos)
			val stateLens = level.getBlockState(posLens)

			if (stateLens.block is BlockGravitationStabilizerLens) {
				level.setBlock(posLens, stateLens.setValue(WorkerState.SEMI_WORKER_STATE, if (findBlackHole != null) WorkerState.WORKING else WorkerState.IDLE), Block.UPDATE_CLIENTS)
			}
		}
	}

	override fun setRemoved() {
		super.setRemoved()
		blackHole?.stabilizerDetached(this)
	}

	override fun getRenderBoundingBox(): AABB {
		return AABB(blockPos.offset(-RANGE, -RANGE, -RANGE), blockPos.offset(RANGE, RANGE, RANGE))
	}

	companion object {
		const val RANGE = 64
	}
}
