|
| 1 | +package com.willfp.ecoenchants.target |
| 2 | + |
| 3 | +import com.github.benmanes.caffeine.cache.Caffeine |
| 4 | +import com.willfp.eco.core.fast.fast |
| 5 | +import com.willfp.ecoenchants.enchant.EcoEnchant |
| 6 | +import com.willfp.ecoenchants.enchant.EcoEnchantLevel |
| 7 | +import com.willfp.libreforge.ProvidedHolder |
| 8 | +import com.willfp.libreforge.slot.ItemHolderFinder |
| 9 | +import com.willfp.libreforge.slot.SlotType |
| 10 | +import com.willfp.libreforge.toDispatcher |
| 11 | +import org.bukkit.entity.LivingEntity |
| 12 | +import org.bukkit.inventory.ItemStack |
| 13 | +import java.util.UUID |
| 14 | +import java.util.concurrent.TimeUnit |
| 15 | + |
| 16 | +object EnchantFinder : ItemHolderFinder<EcoEnchantLevel>() { |
| 17 | + private val provider = this.toHolderProvider() |
| 18 | + private val levelCache = Caffeine.newBuilder() |
| 19 | + .expireAfterWrite(1, TimeUnit.SECONDS) |
| 20 | + .build<UUID, List<ProvidedLevel>>() |
| 21 | + |
| 22 | + override fun find(item: ItemStack): List<EcoEnchantLevel> { |
| 23 | + val enchantMap = item.fast().enchants |
| 24 | + val enchants = mutableListOf<EcoEnchantLevel>() |
| 25 | + |
| 26 | + for ((enchant, level) in enchantMap) { |
| 27 | + if (enchant !is EcoEnchant) { |
| 28 | + continue |
| 29 | + } |
| 30 | + |
| 31 | + enchants += enchant.getLevel(level) |
| 32 | + } |
| 33 | + |
| 34 | + return enchants |
| 35 | + } |
| 36 | + |
| 37 | + override fun isValidInSlot(holder: EcoEnchantLevel, slot: SlotType): Boolean { |
| 38 | + return slot in holder.enchant.targets.map { it.slot } |
| 39 | + } |
| 40 | + |
| 41 | + internal fun LivingEntity.clearEnchantmentCache() = levelCache.invalidate(this.uniqueId) |
| 42 | + |
| 43 | + private val LivingEntity.cachedLevels: List<ProvidedLevel> |
| 44 | + get() = levelCache.get(this.uniqueId) { |
| 45 | + provider.provide(this.toDispatcher()) |
| 46 | + .mapNotNull { |
| 47 | + val level = it.holder as? EcoEnchantLevel ?: return@mapNotNull null |
| 48 | + val item = it.provider as? ItemStack ?: return@mapNotNull null |
| 49 | + |
| 50 | + ProvidedLevel(level, item, it) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + fun LivingEntity.hasEnchantActive(enchant: EcoEnchant): Boolean { |
| 55 | + return this.cachedLevels |
| 56 | + .filter { it.level.enchant == enchant } |
| 57 | + .any { it.level.conditions.areMet(this.toDispatcher(), it.holder) } |
| 58 | + } |
| 59 | + |
| 60 | + fun LivingEntity.getItemsWithEnchantActive(enchant: EcoEnchant): Map<ItemStack, Int> { |
| 61 | + return this.cachedLevels |
| 62 | + .filter { it.level.enchant == enchant } |
| 63 | + .filter { it.level.conditions.areMet(this.toDispatcher(), it.holder) } |
| 64 | + .associate { it.item to it.level.level } |
| 65 | + } |
| 66 | + |
| 67 | + private data class ProvidedLevel( |
| 68 | + val level: EcoEnchantLevel, |
| 69 | + val item: ItemStack, |
| 70 | + val holder: ProvidedHolder |
| 71 | + ) |
| 72 | +} |
0 commit comments