package net.teamio.taam.util;

import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.wrappers.FluidHandlerWrapper;

@SuppressWarnings("deprecation") // Deprecation because of the net.minecraftforge.fluids.IFluidHandler
public final class FluidUtils {
	private FluidUtils() {
		// Util Class
	}

	public static FluidStack getFluidFromItem(ItemStack stack) {
		IFluidHandler fluidHandler = stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, EnumFacing.UP);
		return fluidHandler.drain(1, false);
	}
	
	public static IFluidHandler getFluidHandlerForItem(ItemStack stack) {
		return stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, EnumFacing.UP);
	}
	
	public static IFluidHandler getFluidHandler(IBlockAccess world, BlockPos pos, EnumFacing side) {
		return FluidUtils.getFluidHandler(world.getTileEntity(pos), side);
	}

	public static IFluidHandler getFluidHandler(TileEntity tileEntity, EnumFacing side) {
		if (tileEntity == null) {
			return null;
		}
		IFluidHandler fluidHandler = tileEntity.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side);
		// Wrapper for the old fluid handlers for now - once the old system is removed, this can be removed as well.
		if(fluidHandler == null && tileEntity instanceof net.minecraftforge.fluids.IFluidHandler) {
			fluidHandler = new FluidHandlerWrapper((net.minecraftforge.fluids.IFluidHandler)tileEntity, side);
		}
		return fluidHandler;
	}
}

@@ -713,16 +713,58 @@
 tack) %7B%0A
+%09%09if(stack == null) %7B%0A%09%09%09return null;%0A%09%09%7D%0A
 %09%09IFluid
@@ -871,16 +871,65 @@
 ng.UP);%0A
+%09%09if(fluidHandler == null) %7B%0A%09%09%09return null;%0A%09%09%7D%0A
 %09%09return
@@ -952,9 +952,25 @@
 ain(
-1
+Integer.MAX_VALUE
 , fa
@@ -974,26 +974,25 @@
  false);%0A%09%7D%0A
-%09
 %0A
+
 %09public stat
@@ -1147,17 +1147,16 @@
 UP);%0A%09%7D%0A
-%09
 %0A%09public

Fix NPE when clicking a tank or creative well with a non-fluid-container