package org.minimalj.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;

import org.minimalj.repository.list.QueryResultList;

public class SerializationContainer implements Serializable {

	private static final long serialVersionUID = 1L;

	private transient Object object;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Serializable wrap(Object object) {
		if (object instanceof List && !(object instanceof QueryResultList)) {
			List list = (List) object;
			for (int i = 0; i<list.size(); i++) {
				list.set(i, wrap(list.get(i)));
			}
			return (Serializable) list;
		} else if (object instanceof Serializable) {
			return (Serializable) object;
		} else {
			SerializationContainer container = new SerializationContainer();
			container.object = object;
			return container;
		}
	}
	
	public static Object[] wrap(Object[] objects) {
		Object[] containers = new Object[objects.length];
		for (int i = 0; i<objects.length; i++) {
			containers[i] = wrap(objects[i]);
		}
		return containers;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object unwrap(Object container) {
		if (container instanceof List && !(container instanceof QueryResultList)) {
			List list = (List) container;
			for (int i = 0; i<list.size(); i++) {
				list.set(i, unwrap(list.get(i)));
			}
			return list;
		} else if (container instanceof SerializationContainer) {
			return ((SerializationContainer) container).object;
		} else {
			return container;
		}
	}
	
	public static Object[] unwrap(Object[] containers) {
		Object[] objects = new Object[containers.length];
		for (int i = 0; i<containers.length; i++) {
			objects[i] = unwrap(containers[i]);
		}
		return objects;
	}
	
	private void writeObject(ObjectOutputStream out) throws IOException {
		SerializationOutputStream soo = new SerializationOutputStream(out);
		soo.writeArgument(object);
 	}
	
	private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		SerializationInputStream soo = new SerializationInputStream(in);
		object = soo.readArgument();
	}
	
}

@@ -911,219 +911,8 @@
 %7D%0A%09%0A
-%09public static Object%5B%5D wrap(Object%5B%5D objects) %7B%0A%09%09Object%5B%5D containers = new Object%5Bobjects.length%5D;%0A%09%09for (int i = 0; i%3Cobjects.length; i++) %7B%0A%09%09%09containers%5Bi%5D = wrap(objects%5Bi%5D);%0A%09%09%7D%0A%09%09return containers;%0A%09%7D%0A%09%0A
 %09@Su
@@ -1375,226 +1375,8 @@
 %7D%0A%09%0A
-%09public static Object%5B%5D unwrap(Object%5B%5D containers) %7B%0A%09%09Object%5B%5D objects = new Object%5Bcontainers.length%5D;%0A%09%09for (int i = 0; i%3Ccontainers.length; i++) %7B%0A%09%09%09objects%5Bi%5D = unwrap(containers%5Bi%5D);%0A%09%09%7D%0A%09%09return objects;%0A%09%7D%0A%09%0A
 %09pri

remove unused methods