package framework.io.component;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import framework.component.Component;
import framework.component.ComponentSystem;
import framework.io.CustomInputStream;
public class ComponentLoader {
private static HashMap<String,Integer> baseIDs;
private static Component createComponentFromList(String typeID, DataInputStream in, int baseID, byte versionNum) throws IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException{
Class<Component> componentClass = (Class<Component>) Class.forName(typeID);
return componentClass.getDeclaredConstructor(CustomInputStream.class, Integer.class, Integer.class).newInstance(in, baseID, versionNum);
}
public static Component loadComponent(CustomInputStream in, boolean loadBaseIDs, boolean closeAftrerReading) throws IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException{
if(loadBaseIDs){
baseIDs = ComponentSystem.getInstance().getSafeBaseForAllTypes();
}
final String typeID = in.readString();
final byte versionNum = in.readByte();
final int baseID = baseIDs.get(typeID);
final Component c = createComponentFromList(typeID, in, baseID, versionNum);
if(closeAftrerReading){
in.close();
}
return c;
}
public static Component loadComponent(final File file) throws IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException{
return loadComponent(new CustomInputStream(new BufferedInputStream(new FileInputStream(file))), true, true);
}
public static Component loadComponent(String fileName) throws IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException{
return loadComponent(new File(fileName));
}
}