package ru.dbotthepony.mc.otm.item.consumables

import net.minecraft.ChatFormatting
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.effect.MobEffectInstance
import net.minecraft.world.effect.MobEffects
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.Level
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.core.otmRandom
import ru.dbotthepony.mc.otm.core.position
import ru.dbotthepony.mc.otm.entity.BreadMonster
import ru.dbotthepony.mc.otm.item.MatteryItem
import ru.dbotthepony.mc.otm.registry.game.MDataComponentTypes

class ImperfectBreadItem(properties: Properties) : MatteryItem(properties) {
	override fun finishUsingItem(stack: ItemStack, level: Level, entity: LivingEntity): ItemStack {
		if (entity is ServerPlayer) {
			entity.addEffect(MobEffectInstance(MobEffects.POISON, 80, 2))
		}

		return super.finishUsingItem(stack, level, entity)
	}

	init {
		tooltips.addNormal { itemStack, context, acceptor ->
			if (itemStack[MDataComponentTypes.INERT] == true) {
				acceptor(TranslatableComponent("otm.misc.inert").withStyle(ChatFormatting.DARK_GRAY))
			}
		}
	}

	override fun onEntityItemUpdate(stack: ItemStack, entity: ItemEntity): Boolean {
		if (stack[MDataComponentTypes.INERT] == true)
			return super.onEntityItemUpdate(stack, entity)

		// roll multiple times so multiple bread monsters can spawn on tick
		// and also chance be less biased
		for (i in 0 until stack.count.coerceAtMost(16)) {
			if (entity.level().otmRandom.nextFloat() < 0.001f) {
				val ent = BreadMonster(entity.level())
				ent.position = entity.position
				entity.level().addFreshEntity(ent)
				stack.shrink(1)
			}
		}

		return super.onEntityItemUpdate(stack, entity)
	}
}
