package org.black_ixx.bossshop.managers;

import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

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

/**
 * 用于背包物品检查,背包物品收取
 * @author 聪聪
 *
 */
public class ItemStackChecker{

    public static boolean isSame(ItemStack pItem1,ItemStack pItem2){
        if(pItem1==null&&pItem2==null) return true;
        if(pItem1==null||pItem2==null) return false;
        if(pItem1.getType()!=pItem2.getType()) return false;
        if(pItem1.getDurability()!=pItem2.getDurability()) return false;
        Object tNMSItemStack_mcitem1=NMSHelper.getNMSItem(pItem1);
        Object tNMSItemStack_mcitem2=NMSHelper.getNMSItem(pItem2);
        if(tNMSItemStack_mcitem1==null&&tNMSItemStack_mcitem2==null) return true;
        if(tNMSItemStack_mcitem1==null||tNMSItemStack_mcitem2==null) return false;
        Object tag1=ClassHelper.getFieldValue(tNMSItemStack_mcitem1,NMSHelper.field_NMSItemStack_tag);
        Object tag2=ClassHelper.getFieldValue(tNMSItemStack_mcitem2,NMSHelper.field_NMSItemStack_tag);
        return (tag1==null&&tag2==null)||(tag1!=null&&tag2!=null&&tag1.equals(tag2));
    }
    
    public static boolean inventoryContainsItem(Player p,ItemStack item){
        int a=0;
        int rcount=item.getAmount();
        for(ItemStack ii : p.getInventory().getContents()){
            if(ii==null) continue;
            if(item.getType()!=ii.getType()) continue;
            if(item.getDurability()!=ii.getDurability()) continue;
            if(isSame(ii,item))
                a+=ii.getAmount();
            if(rcount<=a) return true;
        }
        return false;
    }

    public static void takeItem(ItemStack item,Player p){
        int a=0;
        int rcount=item.getAmount();
        ItemStack[] items=p.getInventory().getContents();
        for(int i=0;i<items.length;i++){
            ItemStack ii=items[i];
            if(ii==null) continue;
            if(!isSame(item,ii)) continue;
            int amount=ii.getAmount();
            int remove=a+amount<=rcount?amount:rcount-a;
            a+=remove;
            ii.setAmount(amount-remove);
            items[i]=amount-remove==0?null:ii;
            if(a>=rcount){
                p.getInventory().setContents(items);
                return;
            }
        }
    }

    public static boolean isValidEnchantment(ItemStack item,Enchantment enchantment,int level){
        try{
            item.clone().addEnchantment(enchantment,level);
        }
        catch(Exception e){
            return false;
        }
        return true;
    }

}
