package ru.dbotthepony.mc.otm.core.multiblock

import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap

class MultiblockListenerSet(val parent: IMultiblockAccess) {
	private val referencedListeners = Object2IntOpenHashMap<IMultiblockListener>()

	fun reference(value: IMultiblockListener) {
		val i = referencedListeners.computeInt(value, { _, int -> (int ?: 0) + 1 })

		if (i == 1) {
			value.onAddedToMultiblock(parent)
		}
	}

	fun dereference(value: IMultiblockListener) {
		val i = referencedListeners.computeInt(value, { _, int -> (int ?: 0) - 1 })

		if (i <= 0) {
			referencedListeners.removeInt(value)
			value.onRemovedFromMultiblock(parent)
		}
	}

	fun clear() {
		referencedListeners.keys.forEach { it.onRemovedFromMultiblock(parent) }
		referencedListeners.clear()
	}
}
