package ru.dbotthepony.mc.otm.android

import it.unimi.dsi.fastutil.io.FastByteArrayOutputStream
import net.minecraft.nbt.CompoundTag
import net.minecraftforge.common.util.INBTSerializable
import net.minecraftforge.event.entity.living.LivingAttackEvent
import net.minecraftforge.event.entity.living.LivingHurtEvent
import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability
import ru.dbotthepony.mc.otm.core.nbt.set
import ru.dbotthepony.mc.otm.network.synchronizer.FieldSynchronizer
import java.io.InputStream

abstract class AndroidFeature(val type: AndroidFeatureType<*>, val android: MatteryPlayerCapability) : INBTSerializable<CompoundTag> {
	val ply get() = android.ply
	val synchronizer = FieldSynchronizer()

	open var level by synchronizer.int(setter = setter@{ value, field, setByRemote ->
		if (value != field.read()) {
			field.write(value)
			applyModifiers()
		}
	})

	open fun tickClient() {}
	open fun tickServer() {}

	/**
	 * Called when it is required to network everything again
	 */
	open fun invalidateNetwork() {
		synchronizer.invalidate()
	}

	open fun applyModifiers() {}
	open fun removeModifiers() {}

	open fun onHurt(event: LivingHurtEvent) {}
	open fun onAttack(event: LivingAttackEvent) {}

	open fun collectNetworkPayload(): FastByteArrayOutputStream? {
		return synchronizer.collectNetworkPayload()
	}

	open fun applyNetworkPayload(stream: InputStream) {
		synchronizer.read(stream)
	}

	override fun serializeNBT(): CompoundTag {
		return CompoundTag().also {
			it["level"] = level
		}
	}

	override fun deserializeNBT(nbt: CompoundTag) {
		level = nbt.getInt("level")
	}
}

class DummyAndroidFeature(type: AndroidFeatureType<*>, android: MatteryPlayerCapability) : AndroidFeature(type, android) {
	override fun serializeNBT(): CompoundTag {
		return CompoundTag()
	}

	override fun deserializeNBT(nbt: CompoundTag) {

	}
}

