package net.viddeno.technical.auto.tileentity;

import org.apache.logging.log4j.Level;

import cpw.mods.fml.common.FMLLog;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.viddeno.technical.auto.TechnicalAutoTileEntity;

public class TileEntityGrabberFiltering extends TileEntityGrabber {

	public int getInventoryStackLimit() {
		return 1;
	}

	protected boolean pushItemTechnicalAutoTileEntity() {
		if(debug)
			FMLLog.log(Level.INFO, "fC");
		TechnicalAutoTileEntity pushTileEntity = (TechnicalAutoTileEntity) pushTileEntity();
		if(blockItemStack.stackSize > 1) {
			ItemStack oldStack = blockItemStack.copy();
			ItemStack newStack = blockItemStack.splitStack(1);
			newStack = pushTileEntity.pushItem(newStack, -1);
			if(newStack == null || newStack.stackSize == 0) {
				if(debug)
					FMLLog.log(Level.INFO, "fDa");
				markDirty = true;
			} else {
				blockItemStack = oldStack;
			}
		}
		return markDirty;
	}
	
	protected boolean allowedToPull() {
		return (blockItemStack == null || blockItemStack.stackSize < 2) && pullTileEntity() != null;
	}

	protected boolean pushItemIInventory(IInventory inventory, int slot) {
		if(blockItemStack.stackSize > 1) {
			ItemStack oldStack = blockItemStack.copy();
			ItemStack newStack = blockItemStack.splitStack(1);
			
			if(inventory.getStackInSlot(slot) == null) {
				if(debug)
					FMLLog.log(Level.INFO, "fF");
				inventory.setInventorySlotContents(slot, newStack.copy());
				newStack = null;
				markDirty = true;
			} else if(inventory.getStackInSlot(slot).getItem() == newStack.getItem() && inventory.getStackInSlot(slot).stackSize < inventory.getInventoryStackLimit() && inventory.getStackInSlot(slot).stackSize < inventory.getStackInSlot(slot).getMaxStackSize()) {
				if(debug)
					FMLLog.log(Level.INFO, "fG");
				newStack.stackSize += inventory.getStackInSlot(slot).stackSize;
				inventory.setInventorySlotContents(slot, newStack.copy());
				newStack = null;
				markDirty = true;
			} else {
				if(debug)
					FMLLog.log(Level.INFO, "fGa");
			}
			
			if(newStack == null || newStack.stackSize == 0) {
				if(debug)
					FMLLog.log(Level.INFO, "fDa");
				markDirty = true;
			} else {
				blockItemStack = oldStack;
			}
		}
		return markDirty;
	}
	
	protected boolean pullItemTechnicalAutoTileEntity() {
		if(debug)
			FMLLog.log(Level.INFO, "fI");
		TechnicalAutoTileEntity pullTileEntity = (TechnicalAutoTileEntity) pullTileEntity();
		if(blockItemStack == null || blockItemStack.stackSize == 0) {
			blockItemStack = pullTileEntity.pullItem(-1, 1);
			markDirty = true;
		} else {
			ItemStack pulledItem = pullTileEntity.pullItem(-1, 1, blockItemStack);
			if(pulledItem != null)
				blockItemStack.stackSize += pulledItem.stackSize;
			pulledItem = null;
			markDirty = true;
		}
		return markDirty;
	}
}