package ru.dbotthepony.mc.otm.android.feature

import net.minecraft.world.entity.ai.attributes.AttributeModifier
import net.minecraft.world.entity.ai.attributes.Attributes
import ru.dbotthepony.mc.otm.android.AndroidSwitchableFeature
import ru.dbotthepony.mc.otm.capability.MatteryPlayer
import ru.dbotthepony.mc.otm.client.render.MGUIGraphics
import ru.dbotthepony.mc.otm.client.render.ResearchIcons
import ru.dbotthepony.kommons.math.RGBAColor
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.core.ResourceLocation
import ru.dbotthepony.mc.otm.registry.game.AndroidFeatures

class StepAssistFeature(android: MatteryPlayer) : AndroidSwitchableFeature(AndroidFeatures.STEP_ASSIST, android) {
	override fun applyModifiers() {
		if (!isActive)
			return

		val reach = ply.getAttribute(Attributes.STEP_HEIGHT) ?: return

		reach.removeModifier(MODIFIER_ID)
		reach.addPermanentModifier(AttributeModifier(MODIFIER_ID, (level + 1) * 0.5, AttributeModifier.Operation.ADD_VALUE))
	}

	override fun removeModifiers() {
		ply.getAttribute(Attributes.STEP_HEIGHT)?.removeModifier(MODIFIER_ID)
	}

	private var isShiftKeyDown = false

	private fun sharedTick() {
		if (isActive) {
			if (isShiftKeyDown != ply.isShiftKeyDown) {
				isShiftKeyDown = ply.isShiftKeyDown

				if (isShiftKeyDown) {
					removeModifiers()
				} else {
					applyModifiers()
				}
			}
		}
	}

	override fun tickClient() {
		super.tickClient()
		sharedTick()
	}

	override fun tickServer() {
		super.tickServer()
		sharedTick()
	}

	override fun renderIcon(graphics: MGUIGraphics, x: Float, y: Float, width: Float, height: Float, color: RGBAColor) {
		ResearchIcons.ICON_STEP_ASSIST.render(graphics, x, y, width, height, color = color)
	}

	companion object {
		private val MODIFIER_ID = ResourceLocation(OverdriveThatMatters.MOD_ID, "step_assist_feature")
	}
}
