package com.thebrokenrail.sorcerycraft.spell; import com.thebrokenrail.sorcerycraft.SorceryCraft; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.util.Formatting; import java.util.HashMap; import java.util.Map; public class SpellTag { public static final String SPELL_TAG = "Spells"; public static void setSpells(ItemStack itemStack, Map map) { CompoundTag tag; if (itemStack.hasTag()) { tag = itemStack.getTag(); } else { tag = new CompoundTag(); tag.put(SPELL_TAG, new ListTag()); } assert tag != null; tag.put(SPELL_TAG, createSpellsTag(map)); itemStack.setTag(tag); } public static ListTag createSpellsTag(Map map) { ListTag spells = new ListTag(); for (Map.Entry entry : map.entrySet()) { CompoundTag spell = new CompoundTag(); spell.putString("id", entry.getKey()); spell.putInt("level", entry.getValue()); spells.add(spell); } return spells; } public static Map getSpells(ItemStack itemStack) { return getSpells(itemStack.getTag()); } public static Map getSpells(CompoundTag tag) { if (tag == null) { tag = new CompoundTag(); tag.put(SPELL_TAG, new ListTag()); } Tag spellsTag = tag.get(SPELL_TAG); ListTag spells; if (spellsTag instanceof ListTag) { spells = (ListTag) spellsTag; } else { spells = new ListTag(); } Map map = new HashMap<>(); for (int i = 0; i < spells.size(); i++) { CompoundTag spell = spells.getCompound(i); String id = spell.getString("id"); int level = spell.getInt("level"); if (map.get(id) == null || map.get(id) < level) { map.put(id, level); } } return map; } public static Text getTranslatedSpell(String id, int level) { Text text = new TranslatableText("spell." + SorceryCraft.NAMESPACE + '.' + id); text.formatted(Formatting.GRAY); if (level != 0 || SpellRegistry.getMaxLevel(id) != 1) { text.append(" ").append(new TranslatableText("enchantment.level." + (level + 1))); } return text; } }