package common.tileentity;

import common.collect.Lists;
import common.color.TextColor;
import common.entity.npc.EntityNPC;
import common.inventory.Container;
import common.inventory.ContainerTile;
import common.inventory.InventoryPlayer;
import common.item.ItemStack;
import common.network.Packet;
import common.packet.SPacketUpdateTileEntity;
import common.rng.Random;
import common.tags.TagObject;
import java.util.List;
import common.util.ExtMath;

public abstract class TileEntityDevice extends TileEntityLockable implements IHopper, ITickable {
	public static enum Status {
		OFF(TextColor.DGRAY, "Inaktiv"), 
		COOLING(TextColor.YELLOW, "Abkühlen ..."), 
		RUNNING(TextColor.GREEN, "Aktiv"), 
		OVERHEAT(TextColor.RED, "Überhitzt!"), 
		BROKEN(TextColor.BLACK, "Defekt!");
		
		public final TextColor color;
		public final String name;
		
		private Status(TextColor color, String name) {
			this.color = color;
			this.name = name;
		}
	}
	
	protected final ItemStack[] inventory;
	protected final MachineResource[] resources;
	protected final Random rand = new Random();
	protected int temperature;
	protected Status status = Status.OFF;

	protected TileEntityDevice(int slots, MachineResource ... resources) {
		this.inventory = new ItemStack[slots];
		this.resources = resources;
	}

	protected int getTempIncrement() {
		return -1;
	}
	
	protected int getTempDecrement() {
		return -1;
	}
	
	protected int getMaxTemp() {
		return Integer.MAX_VALUE;
	}
	
	protected abstract boolean executeFunction();
	
	public MachineResource getResource(int slot) {
		return this.resources[slot];
	}
	
	public int getNumResources() {
		return this.resources.length;
	}

	public int getTemperature() {
		return this.temperature;
	}

	public void setTemperature(int temp) {
		this.temperature = temp;
	}

	public Status getStatus() {
		return this.status;
	}

	public void setStatus(Status status) {
		this.status = status;
	}

	public void readTags(TagObject compound) {
		super.readTags(compound);
		
		List<TagObject> nbttaglist = compound.getList("Items");
		this.clear();
		for(int i = 0; i < nbttaglist.size(); ++i) {
			TagObject nbttagcompound = nbttaglist.get(i);
			int j = nbttagcompound.getByte("Slot");

			if(j >= 0 && j < this.inventory.length) {
				this.inventory[j] = ItemStack.readFromTag(nbttagcompound);
			}
		}
		
		nbttaglist = compound.getList("Resources");
		for(MachineResource res : this.resources) {
			res.reset();
		}
		for(int i = 0; i < nbttaglist.size() && i < this.inventory.length; ++i) {
			this.resources[i].readFromNbt(nbttaglist.get(i));
		}

		this.temperature = compound.getInt("Temperature");
		this.status = Status.values()[(int)compound.getByte("Status") % Status.values().length];
	}

	public void writeTags(TagObject compound) {
		super.writeTags(compound);
		
		List<TagObject> nbttaglist = Lists.newArrayList();
		for(int i = 0; i < this.inventory.length; ++i) {
			if(this.inventory[i] != null) {
				TagObject nbttagcompound = new TagObject();
				nbttagcompound.setByte("Slot", (byte)i);
				this.inventory[i].writeTags(nbttagcompound);
				nbttaglist.add(nbttagcompound);
			}
		}
		compound.setList("Items", nbttaglist);
		
		nbttaglist = Lists.newArrayList();
		for(int z = 0; z < this.resources.length; z++) {
			TagObject res = new TagObject();
			this.resources[z].writeToNbt(res);
			nbttaglist.add(res);
		}
		compound.setList("Resources", nbttaglist);

		compound.setInt("Temperature", this.temperature);
		compound.setByte("Status", (byte)this.status.ordinal());
	}

	public int getSizeInventory() {
		return this.inventory.length;
	}

	public ItemStack getStackInSlot(int index) {
		return this.inventory[index];
	}

	public ItemStack decrStackSize(int index, int count) {
		if(this.inventory[index] != null) {
			if(this.inventory[index].size <= count) {
				ItemStack itemstack1 = this.inventory[index];
				this.inventory[index] = null;
				return itemstack1;
			}
			else {
				ItemStack itemstack = this.inventory[index].splitStack(count);

				if(this.inventory[index].size == 0) {
					this.inventory[index] = null;
				}

				return itemstack;
			}
		}
		else {
			return null;
		}
	}

	public ItemStack removeStackFromSlot(int index) {
		if(this.inventory[index] != null) {
			ItemStack itemstack = this.inventory[index];
			this.inventory[index] = null;
			return itemstack;
		}
		else {
			return null;
		}
	}

	public void setInventorySlotContents(int index, ItemStack stack) {
		this.inventory[index] = stack;

		if(stack != null && stack.size > this.getInventoryStackLimit()) {
			stack.size = this.getInventoryStackLimit();
		}
	}

	public boolean hasCustomName() {
		return false;
	}

	public int getInventoryStackLimit() {
		return ItemStack.MAX_SIZE;
	}

	public boolean isUseableByPlayer(EntityNPC player) {
		return this.worldObj.getTileEntity(this.pos) != this ? false
				: player.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D;
	}

	public void openInventory(EntityNPC player) {
	}

	public void closeInventory(EntityNPC player) {
	}

	public boolean isItemValidForSlot(int index, ItemStack stack) {
		return true;
	}

	public void detonate() {
		this.worldObj.newExplosion(null, this.getXPos(), this.getYPos(), this.getZPos(), 5.0f, true, true, false);
	}

	public void update() {
		if(this.worldObj != null && !this.worldObj.client && this.status != Status.BROKEN) {
			int envTemp = (int)this.worldObj.getTemperatureC(this.getPos());
			if(this.executeFunction()) {
				if(this.getTempIncrement() < 0)
					this.temperature = envTemp;
				else
					this.temperature += this.getTempIncrement();
				this.status = this.temperature >= (this.getMaxTemp() * 9) / 10 ? Status.OVERHEAT : Status.RUNNING;
				if(this.temperature > this.getMaxTemp()) {
					this.status = Status.BROKEN;
					this.markDirty();
					this.detonate();
					return;
				}
				else {
					this.markDirty();
				}
			}
			else {
				int dec = this.getTempDecrement();
				if(dec != 0) {
					int prev = this.temperature;
					if(dec < 0)
						this.temperature = envTemp;
					else
						this.temperature -= dec;
					this.temperature = ExtMath.clampi(this.temperature, envTemp, Integer.MAX_VALUE);
					if(prev != this.temperature)
						this.markDirty();
					else
						dec = 0;
				}
				Status prev = this.status;
				this.status = this.temperature >= (this.getMaxTemp() * 9) / 10 ? Status.OVERHEAT : 
					(this.temperature == envTemp ? Status.OFF : Status.COOLING);
				if(dec == 0 && prev != this.status) {
					this.markDirty();
				}
			}
			if(this.temperature < envTemp) {
				this.temperature = envTemp;
				this.markDirty();
			}
		}
	}

	public boolean isEmpty(int slot) {
		if(slot == -1) {
			for(ItemStack itemstack : this.inventory) {
				if(itemstack != null)
					return false;
			}
			return true;
		}
		else {
			return this.inventory[slot] == null || this.inventory[slot].size <= 0;
		}
	}

	public boolean hasAmount(int slot, int amount) {
		if(slot == -1) {
			int n = 0;
			for(ItemStack itemstack : this.inventory) {
				if(itemstack != null && itemstack.size >= 1)
					n += itemstack.size;
			}
			return n >= amount;
		}
		else {
			return this.inventory[slot] != null && this.inventory[slot].size >= amount;
		}
	}

	public boolean isFull() {
		for(ItemStack itemstack : this.inventory) {
			if(itemstack == null || itemstack.size != itemstack.getMaxStackSize()) {
				return false;
			}
		}
		return true;
	}

	public double getXPos() {
		return (double)this.pos.getX() + 0.5D;
	}

	public double getYPos() {
		return (double)this.pos.getY() + 0.5D;
	}

	public double getZPos() {
		return (double)this.pos.getZ() + 0.5D;
	}

	public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) {
		return new ContainerTile(playerInventory, this, this, playerIn);
	}

	public int getField(int id) {
		return 0;
	}

	public void setField(int id, int value) {
	}

	public int getFieldCount() {
		return 0;
	}

	public void clear() {
		for(int i = 0; i < this.inventory.length; ++i) {
			this.inventory[i] = null;
		}
	}
	
	public Packet getDescriptionPacket()
    {
        return new SPacketUpdateTileEntity(this);
    }
    
    public int getColor() {
    	return 0x8080ff;
    }
	
	public abstract String formatDisplay(ContainerTile inv);
}
