package omq.common.util.Serializers;

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

import omq.common.event.Event;
import omq.common.event.EventWrapper;
import omq.common.message.Request;
import omq.common.message.Response;
import omq.exception.SerializerException;
import omq.server.remote.request.RemoteObject;

/**
 * 
 * @author Sergi Toda <sergi.toda@estudiants.urv.cat>
 * 
 */
public class JavaImp implements ISerializer {

	@Override
	public byte[] serialize(Object obj) throws SerializerException {
		try {
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			ObjectOutputStream output = new ObjectOutputStream(stream);
			output.writeObject(obj);

			output.flush();
			output.close();

			byte[] bArray = stream.toByteArray();

			stream.flush();
			stream.close();

			System.out.println("JavaImp serialize size = " + bArray.length);

			return bArray;
		} catch (Exception e) {
			throw new SerializerException("Serialize -> " + e.getMessage(), e);
		}
	}

	@Override
	public Request deserializeRequest(byte[] bytes, RemoteObject obj) throws SerializerException {
		return (Request) deserliazeObject(bytes);
	}

	@Override
	public Response deserializeResponse(byte[] bytes, Class<?> type) throws SerializerException {
		return (Response) deserliazeObject(bytes);
	}

	@Override
	public Event deserializeEvent(byte[] bytes) throws SerializerException {
		EventWrapper wrapper = (EventWrapper) deserliazeObject(bytes);
		return wrapper.getEvent();
	}

	private Object deserliazeObject(byte[] bytes) throws SerializerException {
		try {
			ByteArrayInputStream input = new ByteArrayInputStream(bytes);
			ObjectInputStream objInput = new ObjectInputStream(input);

			Object obj = objInput.readObject();

			objInput.close();
			input.close();

			return obj;
		} catch (Exception e) {
			throw new SerializerException("Deserialize -> " + e.getMessage(), e);
		}
	}

}
