package common.tileentity;

import common.tags.TagObject;

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(TagObject tag) {
		this.amount = tag.getInt("Amount");
		this.capacity = tag.getInt("Capacity");
		this.undercharge = tag.getInt("Under");
		this.overcharge = tag.getInt("Over");
		this.entropy = tag.getInt("Entropy");
	}
	
	public void writeToNbt(TagObject tag) {
		tag.setInt("Amount", this.amount);
		tag.setInt("Capacity", this.capacity);
		tag.setInt("Under", this.undercharge);
		tag.setInt("Over", this.overcharge);
		tag.setInt("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));
	}
}
