package common.attributes;

import java.util.Map;
import java.util.Map.Entry;

import common.collect.Maps;

public class AttributeMap {
	private class AttributeInstance {
		private final Map<Integer, Float> slots = Maps.<Integer, Float>newHashMap();

		private boolean update = true;
		private float value;

		public void applyModifier(int slot, float amount) {
			this.slots.put(slot, amount);
			this.update = true;
		}

		public void removeModifier(int slot) {
			if(this.slots.remove(slot) != null)
				this.update = true;
		}

		public float getAttributeValue() {
			if(this.update) {
				this.value = 0.0f;
				for(Float mod : this.slots.values()) {
					this.value += mod;
				}
				this.update = false;
			}
			return this.value;
		}
	}

	private final Map<Attribute, AttributeInstance> attributes = Maps.<Attribute, AttributeInstance>newHashMap();

	public AttributeMap() {
		for(Attribute attribute : Attribute.values()) {
			this.attributes.put(attribute, new AttributeInstance());
		}
	}

	public float get(Attribute attribute) {
		return this.attributes.get(attribute).getAttributeValue();
	}

	public void remove(Map<Attribute, Float> modifiers, int slot) {
		for(Entry<Attribute, Float> entry : modifiers.entrySet()) {
			this.attributes.get(entry.getKey()).removeModifier(slot);
		}
	}

	public void add(Map<Attribute, Float> modifiers, int slot, int amount) {
		for(Entry<Attribute, Float> entry : modifiers.entrySet()) {
			this.attributes.get(entry.getKey()).applyModifier(slot, entry.getValue() * (float)amount);
		}
	}
}
