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

import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.state.BlockState
import ru.dbotthepony.mc.otm.SERVER_IS_LIVE
import ru.dbotthepony.mc.otm.block.CableBlock
import ru.dbotthepony.mc.otm.capability.MatteryCapability
import ru.dbotthepony.mc.otm.graph.matter.MatterNode
import ru.dbotthepony.mc.otm.graph.storage.StorageGraph
import ru.dbotthepony.mc.otm.graph.storage.StorageNode
import ru.dbotthepony.mc.otm.registry.MBlockEntities

class MatterCableBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : MatteryBlockEntity(MBlockEntities.MATTER_CABLE, p_155229_, p_155230_) {
	val matterNode = object : MatterNode() {
		override fun onNeighbour(direction: Direction) {
			val newState = blockState.setValue(CableBlock.MAPPING_CONNECTION_PROP[direction]!!, true)

			if (newState !== blockState && SERVER_IS_LIVE)
				level?.setBlock(blockPos, newState, Block.UPDATE_CLIENTS)
		}

		override fun onUnNeighbour(direction: Direction) {
			val newState = blockState.setValue(CableBlock.MAPPING_CONNECTION_PROP[direction]!!, false)

			if (newState !== blockState && SERVER_IS_LIVE)
				level?.setBlock(blockPos, newState, Block.UPDATE_CLIENTS)
		}
	}

	init {
		exposeGlobally(MatteryCapability.MATTER_NODE, matterNode)
	}

	override fun setLevel(level: Level) {
		super.setLevel(level)
		matterNode.discover(this)
	}

	override fun setRemoved() {
		super.setRemoved()
		matterNode.isValid = false
	}
}

class StorageCableBlockEntity(p_155229_: BlockPos, p_155230_: BlockState) : MatteryBlockEntity(MBlockEntities.STORAGE_CABLE, p_155229_, p_155230_) {
	val storageNode = object : StorageNode() {
		override fun attachComponents(to: StorageGraph) {}
		override fun removeComponents(from: StorageGraph) {}

		override fun onNeighbour(direction: Direction) {
			val newState = blockState.setValue(CableBlock.MAPPING_CONNECTION_PROP[direction]!!, true)

			if (newState !== blockState && SERVER_IS_LIVE)
				level!!.setBlock(blockPos, newState, Block.UPDATE_CLIENTS)
		}

		override fun onUnNeighbour(direction: Direction) {
			val newState = blockState.setValue(CableBlock.MAPPING_CONNECTION_PROP[direction]!!, false)

			if (newState !== blockState && SERVER_IS_LIVE)
				level!!.setBlock(blockPos, newState, Block.UPDATE_CLIENTS)
		}
	}

	init {
		exposeGlobally(MatteryCapability.STORAGE_NODE, storageNode)
	}

	override fun setLevel(level: Level) {
		super.setLevel(level)
		storageNode.discover(this)
	}

	override fun setRemoved() {
		super.setRemoved()
		storageNode.isValid = false
	}
}

