package ru.dbotthepony.mc.otm.android

import net.minecraft.client.gui.GuiGraphics
import net.minecraft.nbt.CompoundTag
import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability
import ru.dbotthepony.mc.otm.core.math.RGBAColor
import ru.dbotthepony.mc.otm.core.nbt.set

abstract class AndroidSwitchableFeature(type: AndroidFeatureType<*>, android: MatteryPlayerCapability) : AndroidFeature(type, android) {
	var isActive by synchronizer.bool(setter = setter@{ value, access, setByRemote ->
		if (value != access.readBoolean()) {
			access.write(value)

			if (!setByRemote) {
				if (value) {
					applyModifiers()
				} else {
					removeModifiers()
				}
			}
		}
	}).property

	open val allowToSwitchByPlayer: Boolean get() = true
	open val allowToSwitchByPlayerWhileSpectator: Boolean get() = true

	open val maxCooldown: Int get() = 0
	open var cooldown by synchronizer.int().property
	val isOnCooldown: Boolean
		get() = maxCooldown > 0 && cooldown > 0

	val cooldownPercent: Float get() {
		if (maxCooldown <= 0) return 0.0f
		return (cooldown.toFloat() / maxCooldown.toFloat()).coerceIn(0.0f, 1.0f)
	}

	fun putOnCooldown() {
		cooldown = maxCooldown
	}

	// TODO: GuiGraphics is stripped from server dist
	// but it doesn't seem to cause issues?
	abstract fun renderIcon(graphics: GuiGraphics, x: Float, y: Float, width: Float, height: Float, color: RGBAColor = RGBAColor.WHITE)

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

	override fun deserializeNBT(nbt: CompoundTag) {
		super.deserializeNBT(nbt)
		isActive = nbt.getBoolean("isActive")
		cooldown = nbt.getInt("cooldown")
	}

	override fun tickServer() {
		super.tickServer()
		if (cooldown > 0) {
			cooldown--
		}
	}
}
