/*
Copyright (C) 2005 David Green <green@couchpotato.net>
All Rights Reserved.

This file is part of Aelfengard.

Aelfengard is proprietary software. You may not redistribute it without
prior written permission from the copyright holder.
*/

package common.gameevent;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import common.ByteSource;

public abstract class GameEvent implements Serializable, Runnable, ByteSource {
    
    public final byte[] toByteArray() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.close();
            return baos.toByteArray();
        }
        catch (Exception ex) {
            // Shouldn't happen with ByteArrayOutputStream
            throw new RuntimeException(ex);
        }
    }
    
    // declaring ClassCastException because of it's likelihood
    public static GameEvent forByteArray(byte[] b) throws IOException, ClassNotFoundException, ClassCastException {
        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (GameEvent) ois.readObject();
    }

}