package ru.dbotthepony.kstarbound.network.syncher

import ru.dbotthepony.kommons.util.Delegate
import ru.dbotthepony.kstarbound.defs.item.ItemDescriptor
import ru.dbotthepony.kstarbound.item.ItemStack
import java.io.DataInputStream
import java.io.DataOutputStream

// Due to this class observing values... event-based
// "hasChangedSince" in GroupElement had to be removed :( tough shit
// Not that it matters anyway, since even more classes followed to mangle
// event driven updates due to their complexity.
// Creating more efficient system for this case will be major complication of entire system,
// and major complications with little improvement are bad.
open class NetworkedItemStack(protected var itemStack: ItemStack = ItemStack.EMPTY) : NetworkedElement(), Delegate<ItemStack> {
	override fun readInitial(data: DataInputStream, isLegacy: Boolean) {
		itemStack = ItemDescriptor(data).build()
		observedVersion = itemStack.changeset
		bumpVersion()
	}

	override fun writeInitial(data: DataOutputStream, isLegacy: Boolean) {
		itemStack.write(data)
	}

	override fun readDelta(data: DataInputStream, interpolationDelay: Double, isLegacy: Boolean) {
		readInitial(data, isLegacy)
	}

	override fun writeDelta(data: DataOutputStream, remoteVersion: Long, isLegacy: Boolean) {
		writeInitial(data, isLegacy)
	}

	override fun readBlankDelta(interpolationDelay: Double) {}
	override fun enableInterpolation(extrapolation: Double) {}
	override fun disableInterpolation() {}
	override fun tickInterpolation(delta: Double) {}

	private var observedVersion = -1L

	override fun toString(): String {
		return "NetworkedItemStack[$itemStack]"
	}

	override fun accept(t: ItemStack) {
		itemStack = t
		observedVersion = t.changeset
		bumpVersion()
	}

	override fun get(): ItemStack {
		return itemStack
	}

	override fun hasChangedSince(version: Long): Boolean {
		if (observedVersion != itemStack.changeset) {
			observedVersion = itemStack.changeset
			bumpVersion()
		}

		return super.hasChangedSince(version)
	}
}
