Untitled

mail@pastecode.io avatar
unknown
java
a year ago
1.7 kB
2
Indexable
Never
package com.facuu16.flib.util;

import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;

import java.lang.reflect.Field;
import java.util.UUID;

public class ItemUtil {

    private static boolean isNewerApi;

    private ItemUtil() {
        throw new UnsupportedOperationException();
    }

    static {
        try {
            Material.valueOf("PLAYER_HEAD");
            isNewerApi = true;
        } catch (IllegalArgumentException e) {
            isNewerApi = false;
        }
    }

    public static ItemStack getSkull(String url) {
        final ItemStack item = getSkullItem();
        final SkullMeta meta = (SkullMeta) item.getItemMeta();

        if (url == null || url.isEmpty())
            return item;

        final GameProfile profile = new GameProfile(UUID.randomUUID(), null);

        profile.getProperties().put("textures", new Property("textures", url));

        try {
            final Field field = meta.getClass().getDeclaredField("profile");

            field.setAccessible(true);
            field.set(meta, profile);
            item.setItemMeta(meta);
        } catch (IllegalArgumentException | NoSuchFieldException | SecurityException | IllegalAccessException exception) {
            exception.printStackTrace();
        }

        return item;
    }

    public static ItemStack getSkullItem() {
        return isNewerApi ? new ItemStack(Material.valueOf("PLAYER_HEAD")) : new ItemStack(Material.SKULL_ITEM, 1, (short) 3);
    }

}