package common.network;

public abstract class NetHandler {
	private static final ThreadQuickExitException EXIT = new ThreadQuickExitException();

	public static final class ThreadQuickExitException extends RuntimeException {
		private ThreadQuickExitException() {
			this.setStackTrace(new StackTraceElement[0]);
		}

		public synchronized Throwable fillInStackTrace() {
			this.setStackTrace(new StackTraceElement[0]);
			return this;
		}
	}

	public abstract void onDisconnect(String reason);
	
	public void update() {
	}

	public static <T> void checkThread(final Packet<T> packet, final T handler, IThreadListener listener)
			throws ThreadQuickExitException {
		if(!listener.isMainThread()) {
			listener.schedule(new Runnable() {
				public void run() {
					packet.processPacket(handler);
				}
			});
			throw EXIT;
		}
	}

	public static <T> void checkThread(final Packet<T> packet, final T handler, IThreadListener listener, Object check)
			throws ThreadQuickExitException {
		if(check == null && listener.isMainThread()) {
			throw EXIT;
		}
		checkThread(packet, handler, listener);
	}
}
