package framework.component.list;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import framework.component.Component;
import framework.component.filter.ComponentFilter;
public class UniqueIDComponentList implements SingleTypeComponentList{
HashMap<Integer, Component> components = new HashMap<Integer, Component>();
ArrayList<Integer> reusableIDs = new ArrayList<Integer>();
private int maxIDReached = -1;
@Override
public Component getComponent(int uniqueID) {
return components.get(uniqueID);
}
@Override
public ArrayList<Component> getComponents(ComponentFilter filter) {
ArrayList<Component> filteredComponents = new ArrayList<Component>();
synchronized (components) {
for(Component c:components.values()){
if(filter.isValidComponent(c)){
filteredComponents.add(c);
}
}
return filteredComponents;
}
}
@Override
public void addComponent(Component c) {
synchronized (components) {
if(c != null){
if(c.getUniqueID() > maxIDReached){
maxIDReached = c.getUniqueID();
}
components.put(c.getUniqueID(), c);
}
}
}
@Override
public int getNextFreeSlot(boolean reuseOldIDs) {
if(!reuseOldIDs || reusableIDs.size() == 0){
return maxIDReached+1;
}else{
return reusableIDs.remove(0);
}
}
@Override
public Component removeComponent(int uniqueID) {
synchronized (components) {
Component c = components.remove(uniqueID);
reusableIDs.add(uniqueID);
return c;
}
}
@Override
public Collection<Component> getAllComponents() {
return components.values();
}
@Override
public int getSlotOf(Component c) {
return c != null ? c.getUniqueID() : NOT_IN_LIST;
}
@Override
public int getSlotOf(int uniqueID) {
return uniqueID;
}
@Override
public int size() {
return components.size();
}
public int getMaxID(){
return maxIDReached;
}
@Override
public Iterator<Component> iterator() {
return components.values().iterator();
}
}