package com.tikaji.halocraft.common.containers.generators;

import com.tikaji.halocraft.common.containers.ContainerHC;
import com.tikaji.halocraft.common.tileentity.generator.TileEntityFissionGenerator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ICrafting;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;

import java.util.List;

/**
 * Created by Jacob Williams on August 17, 2015 at 17:35.
 */
public class ContainerFissionGenerator extends ContainerHC
{
	private TileEntityFissionGenerator generator;
	private int                        lastCookTime;

	public ContainerFissionGenerator(EntityPlayer player, TileEntityFissionGenerator tileEntityFissionGenerator)
	{
		super(player, tileEntityFissionGenerator, 2);

		generator = tileEntityFissionGenerator;
		lastCookTime = 0;

		//Input
		addSlotToContainer(new Slot(generator, 0, 62, 55));
		addSlotToContainer(new Slot(generator, 1, 98, 55));

		addInventorySlots();
	}

	@Override
	public void addCraftingToCrafters(ICrafting listener)
	{
		super.addCraftingToCrafters(listener);
		listener.func_175173_a(this, generator);
	}

	@Override
	public boolean canInteractWith(EntityPlayer player)
	{
		return generator.isUseableByPlayer(player);
	}

	@Override
	public void detectAndSendChanges()
	{
		super.detectAndSendChanges();

		for (ICrafting crafting : (List<ICrafting>) crafters)
		{
			if (lastCookTime != generator.getField(0))
			{
				crafting.sendProgressBarUpdate(this, 0, generator.getField(0));
			}
		}

		lastCookTime = generator.getField(0);
	}

	@Override
	public ItemStack transferStackInSlot(EntityPlayer player, int slotID)
	{
		ItemStack itemstack = null;
		Slot      slot      = (Slot) this.inventorySlots.get(slotID);

		if (slot != null && slot.getHasStack())
		{
			ItemStack itemstack1 = slot.getStack();
			itemstack = itemstack1.copy();

			if (slotID < numSlots)
			{
				if (!this.mergeItemStack(itemstack1, numSlots, 36 + numSlots, true))
				{
					return null;
				}
				slot.onSlotChange(itemstack1, itemstack);
			}
			else if (generator.isItemValidForSlot(slotID, itemstack1))
			{
				if (!this.mergeItemStack(itemstack1, 0, 1, false))
				{
					return null;
				}
			}
			else if (slotID >= numSlots + 1 && slotID < 26 + numSlots)
			{
				if (!this.mergeItemStack(itemstack1, 27 + numSlots, 36 + numSlots, false))
				{
					return null;
				}
			}
			else if (slotID >= 26 + numSlots && slotID < 35 + numSlots)
			{
				if (!this.mergeItemStack(itemstack1, numSlots, 27 + numSlots, false))
				{
					return null;
				}
			}

			if (itemstack1.stackSize == 0)
			{
				slot.putStack((ItemStack) null);
			}
			else
			{
				slot.onSlotChanged();
			}

			if (itemstack1.stackSize == itemstack.stackSize)
			{
				return null;
			}

			slot.onPickupFromSlot(player, itemstack);
		}

		return itemstack;
	}

	@Override
	public void updateProgressBar(int id, int data)
	{
		generator.setField(id, data);
	}
}
