package common.tileentity;

import common.nbt.NBTTagCompound;

public class MachineResource {
	public static enum Type {
		INPUT, OUTPUT, FUEL, CONTROL;
	}
	
	private final Type type;
	private final String name;
	private int amount;
	private int capacity;
	private int undercharge;
	private int overcharge;
	private int entropy;
	
	public MachineResource(Type type, String name, int cap, int under, int over) {
		this.type = type;
		this.name = name;
		this.capacity = cap;
		this.undercharge = under;
		this.overcharge = over;
	}
	
	public void readFromNbt(NBTTagCompound tag) {
		this.amount = tag.getInteger("Amount");
		this.capacity = tag.getInteger("Capacity");
		this.undercharge = tag.getInteger("Under");
		this.overcharge = tag.getInteger("Over");
		this.entropy = tag.getInteger("Entropy");
	}
	
	public void writeToNbt(NBTTagCompound tag) {
		tag.setInteger("Amount", this.amount);
		tag.setInteger("Capacity", this.capacity);
		tag.setInteger("Under", this.undercharge);
		tag.setInteger("Over", this.overcharge);
		tag.setInteger("Entropy", this.entropy);
	}
	
	public void setValue(int value) {
		this.amount = value;
	}
	
	public void setUndercharge(int value) {
		this.undercharge = value;
	}
	
	public void setOvercharge(int value) {
		this.overcharge = value;
	}
	
	public void setCapacity(int value) {
		this.capacity = value;
	}
	
	public boolean take(int value, boolean over) {
		if((over ? this.undercharge : 0) + this.amount < value)
			return false;
		this.amount -= value;
		return true;
	}
	
	public boolean add(int value, int border, boolean over) {
		if(this.amount + (border >= 1 ? border : value) > (over ? this.overcharge : 0) + this.capacity)
			return false;
		int max = (over ? this.overcharge : 0) + this.capacity - this.amount;
		if(value > max) {
			this.entropy += value - max;
			value = max;
		}
		this.amount += value;
		return true;
	}
	
	public int getValue() {
		return this.amount;
	}
	
	public int getUndercharge() {
		return this.undercharge;
	}
	
	public int getOvercharge() {
		return this.overcharge;
	}
	
	public int getCapacity() {
		return this.capacity;
	}
	
	public int getEntropy() {
		return this.entropy;
	}
	
	public void resetEntropy() {
		this.entropy = 0;
	}
	
	public void reset() {
		this.entropy = this.amount = 0;
	}
	
	public boolean isAtCapacity(boolean over) {
		return this.amount >= (this.capacity + (over ? this.overcharge : 0));
	}
}
