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

import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.gui.GuiGraphics
import net.minecraft.world.entity.ai.attributes.AttributeModifier
import net.minecraftforge.common.ForgeMod
import ru.dbotthepony.mc.otm.android.AndroidSwitchableFeature
import ru.dbotthepony.mc.otm.capability.MatteryPlayerCapability
import ru.dbotthepony.mc.otm.client.render.ResearchIcons
import ru.dbotthepony.mc.otm.core.math.RGBAColor
import ru.dbotthepony.mc.otm.registry.AndroidFeatures
import java.util.*

class StepAssistFeature(android: MatteryPlayerCapability) : AndroidSwitchableFeature(AndroidFeatures.STEP_ASSIST, android) {
	override fun applyModifiers() {
		if (!ForgeMod.STEP_HEIGHT_ADDITION.isPresent || !isActive)
			return

		val reach = ply.getAttribute(ForgeMod.STEP_HEIGHT_ADDITION.get()) ?: return

		reach.removeModifier(MODIFIER_ID)
		reach.addPermanentModifier(AttributeModifier(MODIFIER_ID, type.displayName.toString(), (level + 1) * 0.5, AttributeModifier.Operation.ADDITION))
	}

	override fun removeModifiers() {
		if (!ForgeMod.STEP_HEIGHT_ADDITION.isPresent)
			return

		ply.getAttribute(ForgeMod.STEP_HEIGHT_ADDITION.get())?.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: GuiGraphics, 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 = UUID.fromString("4a3fae46-47a8-a03f-857d-f5c2b2c8f2f4")
	}
}
