package org.black_ixx.bossshop.util;

import java.util.Collection;
import java.util.Map;

import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import cc.util.bossshop.ClassHelper;
import cc.util.bossshop.FBukkit;
import cc.util.bossshop.NMSHelper;

public class AttributeRemover{

    private static boolean useItemFlags;
    private static boolean useReflection;

    public static boolean init(){

        if(ClassHelper.isClassLoaded("org.bukkit.inventory.ItemFlag")){
            useItemFlags=true;
        }else{
            FBukkit.severe("此服务器版本"+ClassHelper.getServerVersion()+"可能无法启用属性移除");
            useReflection=true;
        }
        return true;
    }

    public static ItemStack hideAttributes(ItemStack item,int mFlags){
        if(item==null) return null;
        mFlags=mFlags & 0xFFFFFFFF;
        if(useItemFlags){
            ItemMeta meta=item.getItemMeta();
            for(ItemFlag sFlag : ItemFlag.values()){
                int pos=sFlag.ordinal();
                int value=((1<<pos)&mFlags)>>pos;
                if(value==1) meta.addItemFlags(sFlag);
                else meta.removeItemFlags(sFlag);
                //removeItemFlags
            }
            if(!FBukkit.isItemMetaEmpty(meta))
                item.setItemMeta(meta);
            return item;
        }else if(useReflection&&mFlags>0){
            try{
                Object nmsItemstack=ClassHelper.invokeStaticMethod(NMSHelper.clazz_CraftItemStack,"asNMSCopy",ItemStack.class,item);
                if(nmsItemstack==null) return item;
                Object nbtCompound=ClassHelper.getFieldValue(nmsItemstack,NMSHelper.clazz_NBTTagCompound,-1);
                if(nbtCompound==null){
                    nbtCompound=ClassHelper.getInstance(NMSHelper.clazz_NBTTagCompound);
                    ClassHelper.setFiledValue(nmsItemstack,NMSHelper.clazz_NBTTagCompound,nbtCompound,-1);
                }
                Object nbtList=ClassHelper.getInstance(NMSHelper.clazz_NBTTagList);
                Map<String,Object> map=ClassHelper.getFieldValue(nbtCompound,Map.class,-1);
                map.put("AttributeModifiers",nbtList);
                return (ItemStack)ClassHelper.invokeStaticMethod(NMSHelper.clazz_CraftItemStack,"asCraftMirror",NMSHelper.clazz_NMSItemStack,nmsItemstack);
            }catch(Exception e){}
        }
        return item;
    }

    private static boolean isNullOrEmpty(Collection<?> coll){
        return coll==null||coll.isEmpty();
    }

}
