package ru.dbotthepony.mc.otm.data.condition

import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonObject
import com.google.gson.JsonSerializationContext
import net.minecraft.world.entity.OwnableEntity
import net.minecraft.world.level.storage.loot.LootContext
import net.minecraft.world.level.storage.loot.Serializer
import net.minecraft.world.level.storage.loot.parameters.LootContextParams
import net.minecraft.world.level.storage.loot.predicates.InvertedLootItemCondition
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType
import net.minecraftforge.common.util.FakePlayer
import ru.dbotthepony.mc.otm.NULLABLE_MINECRAFT_SERVER
import ru.dbotthepony.mc.otm.data.get
import ru.dbotthepony.mc.otm.registry.MLootItemConditions

object KilledByRealPlayerOrIndirectly : LootItemCondition, Serializer<KilledByRealPlayerOrIndirectly>, LootItemCondition.Builder {
	override fun test(t: LootContext): Boolean {
		if (t.hasParam(LootContextParams.LAST_DAMAGE_PLAYER) && t[LootContextParams.LAST_DAMAGE_PLAYER] !is FakePlayer) {
			return true
		}

		if (t.hasParam(LootContextParams.KILLER_ENTITY)) {
			val killer = t[LootContextParams.KILLER_ENTITY] as? OwnableEntity

			if (killer != null) {
				val owner = killer.owner

				if (owner != null && owner !is FakePlayer) {
					return true
				}

				val ply = NULLABLE_MINECRAFT_SERVER?.playerList?.getPlayer(killer.ownerUUID ?: return false)
				return ply != null && ply !is FakePlayer
			}
		}

		return false
	}

	override fun getType(): LootItemConditionType {
		return MLootItemConditions.KILLED_BY_REAL_PLAYER_OR_INDIRECTLY
	}

	override fun serialize(p_79325_: JsonObject, p_79326_: KilledByRealPlayerOrIndirectly, p_79327_: JsonSerializationContext) {
	}

	override fun deserialize(p_79323_: JsonObject, p_79324_: JsonDeserializationContext): KilledByRealPlayerOrIndirectly {
		return this
	}

	override fun build(): LootItemCondition {
		return this
	}

	val INVERTED: LootItemCondition = InvertedLootItemCondition.invert(this).build()
}
