package cn.estsh.i3plus.ext.mes.pcn.apiservice.util;

import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class DeepCloneUtil<T> {

    private static <T extends Serializable> T deepClone(T t) throws IOException, ClassNotFoundException {

        T deepClone;
        ObjectInputStream ois = null;
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bais = null;

        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(t);
            bais = new ByteArrayInputStream(baos.toByteArray());
            ois = new ObjectInputStream(bais);
            deepClone = (T) ois.readObject();
        } finally {
            if (null != ois) ois.close();
            if (null != bais) bais.close();
            if (null != oos) oos.close();
            if (null != baos) baos.close();
        }

        return deepClone;
    }

    public static <T extends Serializable> T deepCloneObject(T t) {
        if (null == t) return null;
        try {
            return deepClone(t);
        } catch (IOException | ClassNotFoundException e) {
            return null;
        }
    }

    public static <T extends Serializable> List<T> deepCloneList(List<T> list) {
        if (CollectionUtils.isEmpty(list)) return null;
        List<T> deepCloneList = new ArrayList<>();
        try {
            for (T t : list) deepCloneList.add(deepClone(t));
            return deepCloneList;
        } catch (IOException | ClassNotFoundException e) {
            return null;
        }
    }

}
