package ru.dbotthepony.kstarbound.network.syncher

import ru.dbotthepony.kommons.io.UnsignedVarLongCodec
import java.io.DataInputStream
import java.util.function.Consumer

class EventCounterElement : BasicNetworkedElement<Long, Long>(0L, UnsignedVarLongCodec, UnsignedVarLongCodec, { it }, { it }) {
	var pulled = 0L
		private set

	var ignoreOccurrencesOnLoad = false

	fun trigger() {
		accept(get() + 1L)
	}

	fun pullOccurred(): Boolean {
		return pullOccurrences() != 0L
	}

	fun pullOccurrences(): Long {
		val value = get()
		val delta = value - pulled
		require(delta >= 0L) { "Event counter turned back in time" }
		pulled = value
		return delta
	}

	fun ignoreOccurrences() {
		pulled = get()
	}

	override fun readInitial(data: DataInputStream, isLegacy: Boolean) {
		super.readInitial(data, isLegacy)

		if (ignoreOccurrencesOnLoad)
			pulled = get()
	}

	init {
		valueListeners.addListener(Consumer {
			if (it < pulled)
				pulled = it
		})
	}
}
