package net.sourceforge.pain;
import net.sourceforge.pain.console.*;
import net.sourceforge.pain.data.*;
import net.sourceforge.pain.db.*;
import net.sourceforge.pain.logic.*;
import net.sourceforge.pain.plugin.*;
import net.sourceforge.pain.util.*;
import java.io.*;
import java.util.*;
public final class Core {
	public static final String VERSION = "0.41";
	public static final Map consoleByOwner = new HashMap();//warn:soft link to persistent objects
	private static World world = null;
	private static net.sourceforge.pain.Time time = new net.sourceforge.pain.Time();
	private static ConsoleManager cm = null;
	private static PluginManager plm = null;
	private static PainDB db = null;
	private static LogicLoadingManager logicManager = new LogicLoadingManager(getApplicationPath() + "/classes");
	private Core() {
	}
	public static PainDB getDB() {
		return db;
	}
	public static void setDB(PainDB db) {
		if (Core.db != null) {
			throw new RuntimeException("DB already inited!");
		}
		Core.db = db;
		time.addListener(new WorldSaver());
	}
	public static World getWorld() {
		return world;
	}
	protected static void setWorld(World world) {
		Core.world = world;
	}
	protected static void setConsoleManager(ConsoleManager consoleManager) {
		if (cm != null) {
			throw new RuntimeException("console manager reassigning not supported");
		}
		cm = consoleManager;
		cm.init();
		time.addListener(cm);
	}
	public static ConsoleManager getConsoleManager() {
		return cm;
	}
	public static net.sourceforge.pain.Time getTime() {
		return time;
	}
	public static void processEvent(String eventClassSuffix, Object param) throws Exception {
		Event e = (Event) logicManager.provideEventClass(eventClassSuffix).newInstance();
		e.processEvent(param);
	}
	public static LogicLoadingManager getLogicLoader() {
		return logicManager;
	}
	public static String getApplicationPath() {
		String path = System.getProperty("net.sourceforge.pain.home");
		if (path == null || path.length() == 0) {
			throw new RuntimeException("'net.sourceforge.pain.home' is null");
		}
		return path;
	}
	public static byte[] getFileData(String name) throws IOException {
		Log.debug("Loading file:" + name);
		InputStream is = new FileInputStream(name);
		try {
			byte[] data = new byte[is.available()];
			is.read(data);
			return data;
		} finally {
			is.close();
		}
	}
	public static PluginManager getPluginManager() {
		return plm;
	}
	protected static void setPluginManager(PluginManager plm) {
		Core.plm = plm;
	}
	public static void timeStopped() {
		shutdown();
	}
	public static void shutdown() {
		Log.debug("Flushing all data before exit!");
		try {
			db.flush();
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
		}
		db.close();
		Log.debug("Shutted down.");
		System.exit(0);
	}
	public static Iterator getAllObjects(Class clazz) {
		return db.getDbClass(clazz).extentIterator();
	}
}