package com.capgemini.framework.common;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/** Serialization of a BOMLineHolder tree for tests. */
@Slf4j
public final class SerializationHelper {

    private SerializationHelper() {
        // Nothing to do!
    }

    /**
     * Serialize an Object.<br>
     * 
     * @param object Object the object to serialize.
     * @param filePath String the chosen file path, starting from the root of the project (explicitly needs src/main/resource/etc)
     * 
     * @throws FileNotFoundException if the provided file path does not point to a readable file (or it may not exist)
     * @throws IOException if the file read fails, or the serialization fails
     */
    public static void serialize(final Object object, final String filePath) throws IOException {
        // Opening of a Stream on a file
        File file = new File(filePath);
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            // Serialization of the object
            oos.writeObject(object);
            log.info("File written at: " + file.getCanonicalPath());
        }
    }

    /**
     * Deserialize an {@link Object}.
     * 
     * @param filePath String the file path, starting from the root of the project (explicitly needs src/main/resource/etc)
     * @return the serialized object
     * 
     * @throws FileNotFoundException if the provided file path does not point to a readable file (or it may not exist)
     * @throws IOException if the file read fails or deserialization fails
     * @throws ClassNotFoundException if the class of the object is no longer found/available/compatible
     */
    public static Object deserialize(final String filePath) throws IOException, ClassNotFoundException {
        File file = new File(filePath);
        Object obj;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { // Opening of the flows on a file
            // Deserialization of the object
            obj = ois.readObject();
            return obj;
        }
    }
}
